前端之This的作用域

前端--this关键字

this关键字相必大家都不会陌生,十分的熟悉,今天我主要谈一谈在前端中this关键字的使用

其实其他地方区别不大,主要作用域,实话说,ai也搞不明白这个this的作用域

在VSCode)中,this 的作用域和行为是由你正在使用的编程语言的语法和运行时环境决定的,而不是由 VSCode 本身决定。以下是一些关于 this 作用域的一般概念:

  1. 类方法中:
    在类的方法中,this 通常指向调用该方法的实例对象。例如,在 JavaScript 或 Java 中,this 引用的是当前对象的上下文。

  2. 构造函数中:
    在构造函数中,this 指向正在构造的对象。

  3. 事件处理器中:
    在事件处理器中,this 通常指向触发事件的对象。

  4. 回调函数中:
    在回调函数中,this 的值可能会改变,因为它取决于回调函数是如何被调用的。

  5. 箭头函数中:
    在箭头函数中,this 的值是由外围最近一层非箭头函数决定的。

  6. 全局上下文中:
    在全局上下文中,this 的值通常指向全局对象(在浏览器中是 window,在 Node.js 中是 global)。

  7. 严格模式下:
    在严格模式('use strict')下,函数的 this 如果没有被赋值,默认为 undefined。

在 VSCode 中,你可以使用以下功能来理解和导航 this 的作用域:

  • 智能提示:当你在代码中键入 this. 时,VSCode 会显示可用的属性和方法提示,这可以帮助你理解当前 this 的作用域。

  • 代码导航:你可以使用快捷键(通常是 Ctrl+Click 或 Cmd+Click)来导航到 this 引用的属性或方法的定义。

  • 调试:在调试模式下,你可以在调试控制台中查看 this 的值,以了解其在运行时的作用域。

  • 代码片段:你可以创建自定义的代码片段,包括 this 的使用,以快速插入常用的代码模式。

  • 重构:如果你需要重构代码,VSCode 提供了重命名功能,可以帮助你在整个项目中更新 this 引用的属性或方法。

请记住,this 的具体行为和作用域取决于你使用的编程语言和上下文。不同的语言有不同的规则来决定 this 的值。因此,理解你所使用的语言中的 this 概念是非常重要的。

示例:

我写了一个create.html文件(避免太过繁琐,我就不展示后端代码了),根据逻辑我想要将这个创建博客的信息点击创建按钮后保存下来,然后就会显示已经创建博客的内容

使用vue绑定事件技术,我先将数据从服务器(常说的后端)获取到,然后保存到本地的localstorage中(由于使用了ajax技术,要将数据转化为json格式),然后显示(查看博客)从localstorage中取就可以了

然而最开始我发现创建成功后数据并没有保存到本地的localstorage中

最后检查发现就是因为this.blog并没有正确的指向我要保存的博客数据

最后添加了这行代码使用就可以正常运行了
var that = this;

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>创建博客</title>
  <link rel="stylesheet" href="./Bootstrap/css/bootstrap.min.css">
  <script src="./Bootstrap/js/jquery.js"></script>
  <script src="./Bootstrap/js/bootstrap.js"></script>
  <script src="./js/vue.js"></script>
  <script src="./js/axios.js"></script>
  <script src="./js/config.js"></script>
  <style>
    /* Custom styles */
    .container {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100vh;
    }
    .form-create-blog {
      width: 900px;
      padding: 20px;
      border: 1px solid #ddd;
      border-radius: 5px;
    }
    .form-group {
      margin-bottom: 20px;
    }
    .btn-create {
      margin: 5px 0;
      width: 100%;
    }
  </style>
</head>
<body>
  <div class="container" id="root">
    <form class="form-create-blog">
      <h4 class="form-create-blog-heading text-center">创建博客</h4>
      <div class="form-group">
        <label for="inputTitle">博客标题:</label>
        <input type="text" id="inputTitle" v-model="blog.title" class="form-control" placeholder="请输入博客标题" required>
      </div>
      <div class="form-group">
        <label for="inputContent">博客内容:</label>
        <textarea id="inputContent" v-model="blog.content" class="form-control" placeholder="请输入博客内容" required></textarea>
      </div>
      <div class="form-group">
        <label for="inputTime">创建时间:</label>
        <input type="text" id="inputTime" v-model="blog.time" class="form-control" placeholder="请输入创建时间" required>
      </div>
      <div class="form-group">
        <label for="inputAccount">账户名:</label>
        <input type="text" id="inputAccount" v-model="blog.account" class="form-control" placeholder="请输入账户名" required>
      </div>
      <div class="form-group">
        <label for="inputReadCount">阅读数 (初始为0):</label>
        <input type="number" id="inputReadAmount" v-model.number="blog.readAmount" class="form-control" value="0" required>
      </div>
      <div class="form-group">
        <label for="inputLikeCount">点赞数 (初始为0):</label>
        <input type="number" id="inputLikeAmount" v-model.number="blog.likeAmount" class="form-control" value="0" required>
      </div>
      <button class="btn btn-primary btn-create" type="button" @click="createBlog">创建博客</button>
    </form>
  </div>
</body>
<script>
  Vue.config.productionTip = false;

  new Vue({
    el: '#root',
    data: {
      blog: {
        title: '',
        content: '',
        time: '',
        account: '',
        readAmount: 0,
        likeAmount: 0
      }
    },
    methods: {
      createBlog() {
        //this作用域
        var that = this;
        axios.post('/user/createBlog', this.blog)
          .then(function(response) {
            console.log(response);
            if (response.data === 'ok') {
              alert('博客创建成功!');
              //将博客数据存入localStorage
              // localStorage.setItem('blog', JSON.stringify(this.blog));
              let blogJson = JSON.stringify(that.blog);
              localStorage.setItem('blog', blogJson);
              window.location.href = './see-blog.html';
            } else {
              alert('博客创建失败!');
            }
          })
          .catch(function(error) {
            console.error(error);
            alert('请求失败,请检查网络或服务器状态。');
          });
      }
    }
  });
</script>
</html>

以下是关于上述代码this的详细解释

  1. 方法定义中的 this:
    在 createBlog 方法中,this 指向调用该方法的对象。这通常意味着如果你通过一个对象调用 createBlog(例如 obj.createBlog()),this 将指向 obj。

  2. axios.post 调用中的 this:
    在 axios.post 调用中,this 同样指向 createBlog 方法的调用者。因此,this.blog 指的是调用 createBlog 方法的对象上的 blog 属性。

  3. 回调函数中的 this:
    JavaScript 中的回调函数(如 .then 和 .catch 中的函数)不会继承外部函数的 this 值。这意味着在这些回调函数中,this 不再指向调用 createBlog 的对象,而是指向全局对象(在浏览器中是 window)或者在严格模式下是 undefined。

  4. 使用 var that = this; 保存 this 的值:
    为了避免在回调函数中丢失 this 的值,代码中使用了 var that = this; 来保存 createBlog 方法调用时的 this 值。这样,在回调函数中使用 that 就可以访问到原始的 this 值,即调用 createBlog 的对象。

  5. 在 .then 回调中使用 that:
    在 .then 回调函数中,使用 that 来代替 this,以确保能够正确访问到 blog 对象。例如,let blogJson = JSON.stringify(that.blog); 实际上是将调用 createBlog 方法的对象上的 blog 属性转换为 JSON 字符串。

  6. 在 localStorage 和 window.location 中不需要 this:
    localStorage.setItem 和 window.location.href 都是全局对象的方法,因此它们不需要 this 来调用。

这段代码通过在回调函数外部保存 this 的值到 that 变量中,确保在回调函数内部可以正确地访问到外部作用域中的 this 值。这是一种常见的模式,用于处理 JavaScript 中 this 作用域的问题。

see-blog.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>查看博客</title>
  <link rel="stylesheet" href="./Bootstrap/css/bootstrap.min.css">
  <script src="./Bootstrap/js/jquery.js"></script>
  <script src="./Bootstrap/js/bootstrap.js"></script>
  <script src="./js/vue.js"></script>
  <script src="./js/axios.js"></script>
  <script src="./js/config.js"></script>
  <style>
    .container {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100vh;
    }
    .blog-view {
      max-width: 1000px;
      padding: 20px;
      border: 1px solid #ddd;
      border-radius: 5px;
    }
  </style>
</head>
<body>
  <div class="container" id="root">
    <div class="blog-view">
      <h2>标题{{ blog.title }}</h2>
      <h5>作者:{{ blog.account }}</h5>
      <p>创建时间:{{ blog.time }}</p>
      <div v-html="blog.content"></div>
      <p>阅读数:{{ blog.readAmount }}</p>
      <p>点赞数:{{ blog.likeAmount }}</p>
    </div>
  </div>
</body>
<script>
  Vue.config.productionTip = false;

  new Vue({
  el: '#root',
  data: {
    blog: {}
  },
  created() {
    // 从localStorage中获取博客数据
    try {
    const blogData = localStorage.getItem('blog');
    console.log('blogData:', blogData);
    if (blogData) {
      this.blog = JSON.parse(blogData);
    }
  } catch (error) {
    console.error('Error parsing blog data from localStorage:', error);
  }
  }
});
</script>
</html>
posted @ 2024-11-08 19:12  curry库-04049  阅读(104)  评论(0)    收藏  举报