javascript - `this` 是否指的是它的调用位置或调用方式?

标签 javascript this

我不是在问什么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/

相关文章:

javascript - 将 Owl Carousel 与 Ember 一起使用

javascript - 网络语音 API : Consistently get the supported speech synthesis voices on iOS safari

Javascript Composite模式,无法正确使用覆盖方法

javascript - 调用clearTimeout后setTimeout继续运行

javascript - 更改货币符号或在inputmask货币中将其删除

javascript - "this"不是我想要的

Javascript 函数存储在数组中与存储在变量中

来自 MDN 和书籍的 JavaScript `this` 示例无法正常工作...为什么?

Java 使用新类向现有类添加功能,同时仍然公开先前类的所有方法

javascript - 如何使用 jQuery 获取该元素的索引?