闭包,最后一个return 为什么是The Window?

根据作用域链的原理,最后this.name不应该在object里面找吗?

var name = "The Window";
    var object = {
        name : "My Object",
        getNameFunc : function(){
            alert("My Object "+this.name); //MyObject
            return function () {
                alert("The Window "+this.name);
                return this.name;//This Window
            }
        }
    };
阅读 2.8k
4 个回答

你这段代码其实没有必要用 作用域链 来解释

函数体内部的this指向是根据函数调用者来决定的。

我完善了一下你的代码,你应该能理解了。

var name = "The Window";
  var object = {
    name: "My Object",
    getNameFunc: function () {
      console.log("My Object ====>" + this.name); //MyObject
      return function () {
        console.log("The Window =====>" + this.name);
        console.log('this.name ====>'+this.name) ;//This Window
      }
    }
  };
  var obj = object.getNameFunc();
  obj();
  obj.call(object); // 这里通过call方法,改变了函数内部的this指向
var name = "The Window";
var object = {
    name : "My Object",
    getNameFunc : function(){
        alert("My Object "+this.name); //MyObject
        var self = this; // 保存this
        return function () {
            // 函数内, 非 use strict; this 指向window
            alert("The Window "+self.name);
            return self.name; // 使用self替换this
        }
    }
};

或者定义个方法封装

function context(fn, ctex){
    return function(){ return fn.apply(ctex, arguments)}
}

// getNameFunc 方法改为:
getNameFunc : function(){
    alert("My Object "+this.name); //MyObject
    return context(function () {
        alert("The Window "+this.name);
        return this.name;
    }, this) // << 传递this至函数内
}

来个context实例

function showName(){
    return this.test_name;
}

alert( showName() ); // >> undefined

var data = {test_name:"hello"};
showName = context(showName, data);
alert( showName() ); // >> hello

this跟根据函数实际调用情况来确定指向,因而你题目没有实际调用情况,我们是没法确定this到底指向了什么

看返回的这个函数所处的环境是什么

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题