三个代码示例理解js中的this

原文链接:https://www.cnblogs.com/yalong/p/14548378.html

示例一:

JavaScript里,this 的值在函数被调用的时候才会指定, 看如下代码:

 let person = {
      name: '小明',
      age: 16,
      say: function() {
          return function() {
            return {name: this.name, age: this.age, obj: this};
          }
      }
    }

  let say = person.say();
  let p = say(); // 函数实际是在这里调用,此时 this 是指向 Window

  console.log(p)

输出的结果如下:

 解释说明:

  因为最终调用的是 say(), 这时候 this是指向window的 (注意: 严格模式下,this是undefined 而不是window)

示例二:

为了把this当做person用, 可以使用箭头函数,因为箭头函数能保存函数创建时的this, 而不是调用时的值, 看如下代码:

let person = {
name:
'小明', age: 16, say: function() {
      // 箭头函数创建的时候, 箭头函数里面的this, 用的是这里的this
      // console.log(this) // 这个this 就是person
return () => { return {name: this.name, age: this.age, obj: this}; } } } let say = person.say(); let p = say(); console.log(p)

输出结果如下:

 示例三:

如果把say 也写成箭头函数呢,看如下代码

let person = {
      name: '小明',
      age: 16,
      say: () => { // 这里也写成箭头函数了,那么此时的this 指向的是window
          return () => {
            return {name: this.name, age: this.age, obj: this};
          }
      }
    }

  let say = person.say();
  let p = say();

  console.log(p)

输出结果跟示例一 是一样的, 因为say 是处在person对象环境里的, person对象的this 是指向window的

 

posted @ 2021-03-17 11:35  进军的蜗牛  阅读(150)  评论(0编辑  收藏  举报