JavaScript 匿名函数中的 this 值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8670877/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 07:00:40  来源:igfitidea点击:

this value in JavaScript anonymous function

javascriptecmascript-6thisanonymous-function

提问by Coen

Can anybody explain to me why Ais true and Bis false? I would have expected B to be true as well.

谁能向我解释为什么A是真的,为什么B是假的?我也希望 B 是真的。

function MyObject() {

};

MyObject.prototype.test = function () {
    console.log("A", this instanceof MyObject);
    (function () {
        console.log("B", this instanceof MyObject);
    }());
}

new MyObject().test();

update: since ecmascript-6 you can use arrow functions which would make it easy to refer to MyObject like this:

更新:从 ecmascript-6 开始,您可以使用箭头函数,这样可以轻松地像这样引用 MyObject:

function MyObject() {

};

MyObject.prototype.test = function () {
    console.log("A", this instanceof MyObject);
    (() => {//a change is here, which will have the effect of the next line resulting in true
        console.log("B", this instanceof MyObject);
    })(); //and here is a change
}

new MyObject().test();    

采纳答案by Cameron

thisis special. It refers to the object that the function is being called on behalf of (most commonly via dot syntax).

this很特别。它指代代表调用函数的对象(最常见的是通过点语法)。

So, in the case of A, the function is being called on behalf of a new MyObjectobject. Bis in a different function that isn't explicitly being called on behalf of any object, so thisdefaults to the global object (window).

因此,在 的情况下A,代表新MyObject对象调用该函数。B位于一个不同的函数中,该函数未代表任何对象显式调用,因此this默认为全局对象 ( window)。

In other words, thischanges depending on how the function is called, not where or how it is defined. The fact that you're using an anonymous function (defined inside another function) is coincidental and has no effect on the value of this.

换句话说,this变化取决于函数的调用方式,而不是定义的位置或方式。您使用匿名函数(在另一个函数中定义)的事实是巧合,对 的值没有影响this

回答by Adam Rackis

Inside of your anonymous function thisis the global object.

匿名函数内部this是全局对象。

Inside of test, this is the instance of MyObjecton which the method was invoked.

在 内部test,这是MyObject调用方法的实例。



Whenever you call a function like this:

每当你调用这样的函数时:

somceFunction(); // called function invocation

thisis alwaysthe global object, or undefinedin strict mode (unless someFunctionwas created with bind**— see below)

this永远全局对象,或undefined在严格模式下(除非someFunction与创建bind**-见下文)

Whenever you call a function like this

每当你调用这样的函数时

foo.someMethod();  //called method invocation

thisis set to foo

this被设定为 foo



**EcmaScript5 defines a bindfunction that allows you to create a function that has a pre-set value for this

**EcmaScript5 定义了一个bind函数,该函数允许您创建一个具有预设值的函数this

So this

所以这

    var obj = { a: 12 };
    var someFunction = (function () { alert(this.a); }).bind(obj);
    someFunction();

Causes someFucntionto be invoked with thisequal to obj, and alerts 12. I bring this up only to note that this is a potential exception to the rule I mentioned about functions invoked as

导致someFucntion调用this等于obj,并警告 12。我提出这个只是为了注意这是我提到的关于调用函数的规则的潜在例外

someFunction();

always having thisequal to the global object (or undefinedin strict mode)

始终this等于全局对象(或undefined在严格模式下)

回答by ThiefMaster

In the anonymous function, thisis bound to the global object (windowin a browser environment).

在匿名函数中,this绑定到全局对象(window在浏览器环境中)。

There are various ways of accessing the instance:

有多种访问实例的方式:

var self = this;
(function () {
    console.log("B", self instanceof MyObject);
}());

or

或者

(function () {
    console.log("B", this instanceof MyObject);
}).call(this);

回答by SLaks

thisis set based on how you call the function.
Your anonymous function is a normal function call, so thisis the global object.

this是根据您调用函数的方式设置的。
您的匿名函数是一个普通的函数调用,this全局对象也是。

You could write (function() { ... }).call(this)to explicitly call it with your this.

您可以写入(function() { ... }).call(this)以使用您的this.