This question already has answers here:
What does “this” mean in jQuery? [duplicate]
                            
                                (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。在这种情况下,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

07-24 09:50
查看更多