javascript - 'this' 在原型(prototype)中指什么?

标签 javascript inheritance prototype lexical-scope

假设我们有以下示例:

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

然后我们就有了原型(prototype)引用 foo 的新对象:

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

输出如下:

Kristopher
Jane

但我希望“this”指的是原型(prototype)函数的上下文。如果每个新对象仅引用原型(prototype),我认为会输出以下内容:

Jane
Jane

为什么情况并非如此?我认为由于 Foo 是 b1 和 b2 的共享原型(prototype),因此修改 this.me会覆盖 b1 和 b2 的变量吗?

最佳答案

让我们分解一下:

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

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

b1.init("Kristopher");

您使用“Kristopher”作为参数调用了init。在本例中,thisb1init 会将“Kristopher”指定为 b1me

b2.init("Jane");

您使用“Jane”作为参数调用了init。在本例中,thisb2init 会将“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

关于javascript - 'this' 在原型(prototype)中指什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56083185/

相关文章:

javascript - ES6 功能组件 React.js 中的 Getters

javascript - 我正在尝试仅将不透明度降低到所选元素,但它会将其添加到所有 Javascript

eval 反序列化后 Javascript 原型(prototype)未定义

c# - 为什么将两个字符串作为对象进行比较会导致意外结果

javascript - JS继承原型(prototype)时如何传递参数?

javascript - 理解 JS 的原型(prototype)编程范式

java - 如何将图像从java小程序发送到javascript?

函数中的 Javascript eval

c++ - C++中的继承语法

Java继承ArrayList类型in方法