请帮忙解释一道关于this的面试题?

var name = "小明",
    person = {
      name : "小红",
      getName : function(){
       return function(){
         return this.name;
       };
      }
    };

console.log(person.getName()()); // 小明

为什么最后打印出来的“小明”而不是“小红”?
看不太懂person.getName()()这句后面两个括号的意思。
//新手勿喷,谢谢

阅读 1.9k
3 个回答

person.getName()结果为一个函数:

function(){
    return this.name;
}

person.getName()()即执行这个返回的函数,函数内容是return this.name。此时,作用域为全局,所以this.name等同于window.name也就是“小名”

这是作用域的问题了,
最后的()是自执行

var name = "小明",
    person = {
      name : "小红",
      getName : function(){
        var _this = this;
       return function(){
         return _this.name;
       };
      }
    };

console.log(person.getName()()); //小红
var name = "小明",
    person = {
      name : "小红",
      age: 20,
      getName : function(){
       return function(){
         return this.name;
       };
      }
    };
  person.getName() // 这个的结果: function(){return this.name;}
  
  // 此时后面再加上括号执行这个函数
  var n = (function(){
     return this.name;
  })()  // 这里相当于window在调用,一次查找作用域的起始首先是找window,刚好window中有个name值为“小明”
  console.log(n)  // '小明'
  var a = (function(){
     return this.age;
  })()
  console.log(a)  // undefined
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题