javascript - 关于闭包的问题,一个前端面试题(经典)
怪我咯
怪我咯 2017-04-10 15:18:28
0
16
1153

var name = "The Window";
  var object = {
    name : "My Object",
    getNameFunc : function(){
      return function(){
        return this.name;
     };
    }
};
alert(object.getNameFunc()()); //The Window。谁知道这个为什么会打印this window吗?对闭包不是很熟悉,请教你们一下。为什么调用的时候是window这个对象来调用的呢?

怪我咯
怪我咯

走同样的路,发现不同的人生

Antworte allen(16)
洪涛

《javascript高级程序设计》 182页,7.2.2关于this对象,就是这个程序。里面有一句很关键的话

匿名函数的执行环境具有全局性,因此其this对象通常指向window。

Peter_Zhu

此問題和閉包無關。

js 的作者 Brendan Eich 這樣設計,是爲了讓任何不是以 a.b() 形式調用的函數看上去像是 window 對象的方法:

也就是說,b() 等價於 window.b()

然而事實證明這一設計反直覺(其實 js 最初設計時沒有閉包,也就考慮不到閉包中的函數不該看作 window 的方法了)。

所以 ES6 新增了的 arrow function 可以按照題主的直覺執行了:

var name = "The Window";
var object = {
    name: "My Object",
    getNameFunc: function() {
        return () => {
            return this.name; // "this" is the same as getNameFunc
        };
    }
};
小葫芦
var name = "The Window";
  var object = {
    name : "My Object",
    getNameFunc : function(){
      return function(){
        return this.name;
     };
    }
};
object.getNameFunc()只是函数的引用,函数体是
function (){
        return this.name;
     }
当调用这个函数 object.getNameFunc()() ,this指向的当然是 window
黄舟

看看这篇:一个js闭包问题的解答

迷茫

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

return回去的方法,this指向的是window,除非:

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

把函数名和函数功能分开来看。alert(object.getNameFunc()());,函数功能是在全局作用域下实现的,所以指向window

巴扎黑

这个不是闭包的问题。
object.getNameFunc()()相当于

var temp = object.getNameFunc();
temp();
//所以this 是 window(如果不加 'use strict'的话)
Ty80

javascriptthis 指向的是引用

巴扎黑

我在浏览器环境中跑了下结果的确如此,但是在node环境下结果是undefined,有人知道为什么么?

小葫芦
var name = "The Window";

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

var func = object.getNameFunc();

alert(func());

说实话,不觉得有多经典………………

另外这题也与闭包无关

Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!