我不是在问什么this
是。我目前正在重读《You Don't Know JS: this & Object Prototypes》一书,以了解这一点。但是书中有两个地方作者说了两件事(至少看起来是这样)。
第一个定义:
this
binding has nothing to do with where a function is declared, but has instead everything to do with the manner in which the function is called.
第二个定义:
this
is actually a binding that is made when a function is invoked, and what it references is determined entirely by the call-site where the function is called.
第一个明确指出,它不是关于从哪里调用的,而是关于如何调用的。第二个说this
是关于从哪里调用它的。
弄清楚什么this
解决了,我需要查看调用站点(或调用函数的位置),对吧?这意味着“什么是 this
”是一个 where 问题,而不是一个 how 问题,对吧?我需要查看它在哪里被调用,而不是它是如何被调用的。
例如:
let test = {
a: 42
}
function foo(){
console.log(this.a);
}
foo.call(test);
Foo
通过测试显式调用,其中 this
将解析为 test
范围。正确的?因此,要回答“this
是什么”这个问题,我必须看看它是从哪里调用的,对吧?
另一个例子:
let test = {
a: foo,
b: 42
}
function foo(){
console.log(this.b);
}
test.a();
我正在调用foo
通过 test
,所以要找出什么this
决定,我必须看看foo
在哪里是叫来的吧?
再说一遍,我(或多或少)明白如何this
作品。我只是对它的书面定义感到困惑。
最佳答案
The first one explicitly states that it's not about where it's called from ...
不,它声明它与声明的位置无关。
这两种说法都说的是同一件事,但我理解这种困惑。当第二句话说“完全由调用站点决定”时,意思是因为调用站点决定了如何。也称为“函数调用方式”,支持第一条语句。
关于javascript - `this` 是否指的是它的调用位置或调用方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49355631/