这个值在JavaScript匿名函数中 [英] this value in JavaScript anonymous function
问题描述
有人可以向我解释为什么 A
为真且 B
为假?我本以为B也是如此。
Can anybody explain to me why A
is true and B
is false? I would have expected B to be true as well.
function MyObject() {
};
MyObject.prototype.test = function () {
console.log("A", this instanceof MyObject);
(function () {
console.log("B", this instanceof MyObject);
}());
}
new MyObject().test();
推荐答案
此
很特别。它指的是代表函数被调用的对象(最常见的是通过点语法)。
this
is special. It refers to the object that the function is being called on behalf of (most commonly via dot syntax).
因此,在 A的情况下
,代表新的 MyObject
对象调用该函数。 B
处于一个不代表任何对象显式调用的不同函数中,因此此
默认为全局对象(窗口
)。
So, in the case of A
, the function is being called on behalf of a new MyObject
object. B
is in a different function that isn't explicitly being called on behalf of any object, so this
defaults to the global object (window
).
换句话说,此
根据函数的调用方式进行更改,而不是在何处或如何定义。你使用匿名函数(在另一个函数中定义)的事实是巧合的,并且对这个
的值没有影响。
In other words, this
changes 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
.
这篇关于这个值在JavaScript匿名函数中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!