js闭包与this指向

片段1:

 var name = "The Window";

  var object = {
    name : "My Object",

    getNameFunc : function(){
      return function(){
        return this.name;
      };

    }

  };

  alert(object.getNameFunc()());   //"The Window"

片段2:

var name = "The Window";

  var object = {
    name : "My Object",

    getNameFunc : function(){
      var that = this;
      return function(){
        return that.name;
      };

    }

  };

  alert(object.getNameFunc()());   // "My Object"

 

试试以下代码:
var tt = 10;
sss = 100;
function dd(){
  console.log(this);
}
dd();
输出的则是:window对象


那这个时候上面就不难理解了:

return function(){
  this.name
}

这个是一个匿名函数不是object对象的属性和成员函数,则匿名函数中的this指向的肯定是window对象了,this.name 相当于 window.name 上面的那么定义的变量name 是迷惑你的,输出的是

name: "The Window"   

 

this对象是在运行时基于函数的执行环境绑定的:在全局函数中,this等于window,而当函数被作为某个对象的方法调用时,this等于那个对象。不过,匿名函数的执行环境具有全局性,因此其this对象通常指向window。

posted @ 2021-08-20 10:22  是灯芯呀  阅读(153)  评论(0)    收藏  举报