【问题标题】:what does 'this' refer to in a prototype? [duplicate]原型中的“this”指的是什么? [复制]
【发布时间】:2019-05-10 18:39:20
【问题描述】:

假设我们有以下示例:

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 的变量?

【问题讨论】:

  • this 指的是 current 调用上下文。在这种情况下,这是由Object.create 创建并存储在例如b1 中的实例。原型不受影响。如果是这样,那么如果从原型继承的所有东西都只修改该原型,那么整个原型链将毫无用处。
  • @VLAZ 太棒了,谢谢。你能回答我吗,这样我就可以接受了

标签: javascript inheritance prototype lexical-scope


【解决方案1】:

让我们分解一下:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-06
    • 2012-01-16
    • 2011-09-30
    • 2011-09-13
    • 1970-01-01
    • 2011-05-10
    相关资源
    最近更新 更多