This question already has answers here:
What does “this” mean in jQuery? [duplicate]
(6个答案)
12个月前关闭。
假设我们有以下示例:
然后,我们有了新对象,其原型引用了foo:
输出如下:
但是我希望“ this”能够引用原型函数的上下文。如果每个新对象仅引用原型,我认为将输出以下内容:
为什么不是这样?我以为Foo是b1和b2的共享原型,修改
这些行使用
您以“ Kristopher”作为参数调用了
您以“ Jane”作为参数调用了
打印两个对象的
一种简单的表达方式是
(6个答案)
12个月前关闭。
假设我们有以下示例:
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”作为参数调用了
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