假设我们有以下示例:
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
。在本例中,this
是 b1
。 init
会将“Kristopher”指定为 b1
的 me
。
b2.init("Jane");
您使用“Jane”作为参数调用了init
。在本例中,this
是 b2
。 init
会将“Jane”分配为 b2
的 me
。
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/