js中this的引用

278 阅读1分钟

最近被js 闭包中this的使用搞混了。索性恶补了一下 this 的相关知识。

重点: this的指向是由它所在函数调用的上下文决定的。

贴个经典的例子。

  var name = "The Window";
  var object = {
    name : "My Object",
    getNameFunc : function(){

         //此处this 指向object

      return function(){

// 此处this指向window对象

        return this.name;
      };
    }
  };
  alert(object.getNameFunc()());


 var name = "The Window";
  var object = {
    name : "My Object",
    getNameFunc : function(){
      var that = this;
      return function(){
        return that.name;
      };
    }
  };
  alert(object.getNameFunc()());