'this' 在原型中指的是什么?

what does 'this' refer to in a prototype?

假设我们有以下示例:

const Foo = {
  init: function(who) {
    this.me = who;
  },
  speak: function() {
    console.log(this.me);
  }
};

然后我们有新的对象,其原型引用 foo:

  const b1 = Object.create(Foo);
  const b2 = Object.create(Foo);
  b1.init("Kristopher");
  b2.init("Jane");
  b1.speak();
  b2.speak();

输出如下:

Kristopher
Jane

但我本以为 "this" 会引用原型函数的上下文。如果每个新对象仅仅引用原型,我认为会输出以下内容:

Jane
Jane

为什么不是这样呢?我认为由于 Foo 是 b1 和 b2 的共享原型,所以修改 this.me 会覆盖 b1 和 b2 的变量吗?

让我们分解一下:

const b1 = Object.create(Foo);
const b2 = Object.create(Foo);

这些行创建两个单独的实例,使用 Foo 作为原型。

b1.init("Kristopher");

您以 "Kristopher" 作为参数调用了 initthis 在这种情况下是 b1init 会将 "Kristopher" 分配为 b1me

b2.init("Jane");

您以 "Jane" 作为参数调用了 initthis 在这种情况下是 b2init 会将 "Jane" 分配为 b2me

b1.speak();
b2.speak();

打印两个对象的 me

更简单的说法是 this 的值在你写的时候不是固定的(这让你以为它是 Foo)。这取决于函数调用时是如何调用的。

const obj = { somefunc() { ... } }

obj.somefunc() // this === obj

const foo = obj.somefunc
foo() // this == window in non-strict mode, this === undefined in strict mode

const arr = []

const bound = obj.somefunc.bind(arr)
bound() // this === arr

obj.somefunc.call(arr) // this === arr
obj.somefunc.apply(arr) // this === arr