JavaScript 匿名函数中的 this 值 [英] 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();
更新:从 ecmascript-6 开始,您可以使用箭头函数,这样可以轻松地像这样引用 MyObject:
update: since ecmascript-6 you can use arrow functions which would make it easy to refer to MyObject like this:
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();
推荐答案
this
很特别.它指代代表调用函数的对象(最常见的是通过点语法).
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
在一个不同的函数中,它没有被明确地代表任何对象调用,所以 this
默认为全局对象 (window
).
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
).
换句话说,this
的变化取决于函数的调用方式,而不是它的定义位置或方式.您使用匿名函数(在另一个函数中定义)的事实是巧合,对 this
的值没有影响.
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 匿名函数中的 this 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!