Javascript “这”在原型中指的是什么?

Javascript “这”在原型中指的是什么?,javascript,inheritance,prototype,lexical-scope,Javascript,Inheritance,Prototype,Lexical Scope,假设我们有以下示例: 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.ini

假设我们有以下示例:

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
但我希望这是指原型函数的上下文。如果每个新对象仅引用原型,我认为将输出以下内容:

Jane
Jane
为什么不是这样?我认为既然Foo是b1和b2的共享原型,那么修改this.me会覆盖b1和b2的变量吗

让我们把它分解一下:

const b1 = Object.create(Foo);
const b2 = Object.create(Foo);
这些行使用Foo作为原型创建两个单独的实例

b1.init("Kristopher");
你以克里斯托弗为论据打电话给init。在这种情况下,这是b1。init会指定Kristopher为b1的我

你用Jane作为参数调用init。在本例中,这是b2。init会指定Jane为b2的我

打印两个对象的me

一个更简单的说法是,在你写它的时候,它的值不是固定的,这让你觉得它是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

这是指当前调用上下文。在本例中,这是由Object.create创建并存储在b1中的实例。原型不受影响。如果是的话,那么整个原型链将是非常无用的,如果所有从原型派生的东西都只会修改原型。@VLAZ真棒,谢谢。你能给我一个答案让我接受吗
b1.speak();
b2.speak();
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