鍍金池/ 問答/HTML/ 請幫忙解釋一道關(guān)于this的面試題?

請幫忙解釋一道關(guān)于this的面試題?

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

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

為什么最后打印出來的“小明”而不是“小紅”?
看不太懂person.getName()()這句后面兩個括號的意思。
//新手勿噴,謝謝

回答
編輯回答
薔薇花

person.getName()結(jié)果為一個函數(shù):

function(){
    return this.name;
}

person.getName()()即執(zhí)行這個返回的函數(shù),函數(shù)內(nèi)容是return this.name。此時,作用域為全局,所以this.name等同于window.name也就是“小名”

2018年4月28日 13:35
編輯回答
野橘

這是作用域的問題了,
最后的()是自執(zhí)行

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

console.log(person.getName()()); //小紅
2017年7月28日 06:17
編輯回答
吢涼
var name = "小明",
    person = {
      name : "小紅",
      age: 20,
      getName : function(){
       return function(){
         return this.name;
       };
      }
    };
  person.getName() // 這個的結(jié)果: function(){return this.name;}
  
  // 此時后面再加上括號執(zhí)行這個函數(shù)
  var n = (function(){
     return this.name;
  })()  // 這里相當(dāng)于window在調(diào)用,一次查找作用域的起始首先是找window,剛好window中有個name值為“小明”
  console.log(n)  // '小明'
  var a = (function(){
     return this.age;
  })()
  console.log(a)  // undefined
2017年6月28日 01:17