此关键字是构造函数中的窗口对象 [英] this keyword is window object within a constructor function

查看:71
本文介绍了此关键字是构造函数中的窗口对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以我认为我理解这一点(没有双关语意),但显然不是。

Ok, so I thought I understood this (no pun intended), but apparently not.

var Constructor = function () {
    var internalFunction = function () {
        return this === window;
    };
    this.myMethod = function () {
        alert(internalFunction());
    };
};
var myObj = new Constructor();
myObj.myMethod();

此提醒 true 。为什么内部函数不能将这个作为对象?相反,我必须在 myMethod 中使用 alert(internalFunction.call(this));

This alerts true. Why can't the internal function see this as the object? Instead I have to use alert(internalFunction.call(this)); in myMethod.

修改:我一直在寻找解释为什么以这种方式分配此的解释,而不是如 var self = this; 等。对不起,如果我没说清楚。

I was looking for an explanation as to why this is assigned in that way, not workarounds such as var self = this;, etc. Sorry if I didn't make that clear.

推荐答案

在调用函数之前不受约束,并且取决于函数的调用方式。您可以将其视为隐式传递给函数的额外参数。

this is not bound until the function is called and is dependent on how the function is called. You could think of it as an extra parameter implicitly passed to the function.

在这种情况下,问题是您正在调用 internalFunction 使用 internalFunction()。通过调用函数作为方法来设置值(如 foo.bar() foo [bar]())或通过 call()显式设置 apply()。你的电话既没有这么做,所以这个恢复到全局对象。

In this case, the problem is that you're calling internalFunction using internalFunction(). The this value is set either by calling a function as a method (as in foo.bar() or foo["bar"]()) or by setting this explictly via call() or apply(). Your call is doing neither so this reverts to the global object.

实现你想要的最简单方法这种情况下保持 internalFunction private是在构造函数中存储对 this 的引用:

The simplest way to achieve what you want in this case while keeping internalFunction private is to store a reference to this inside the constructor function:

var Constructor = function() {
    var thisObj = this;

    var internalFunction = function () {
        return thisObj === window;
    };

    thisObj.myMethod = function () {
        alert(internalFunction());
    };
}

这篇关于此关键字是构造函数中的窗口对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆