为什么原型中的 'this' 指的是全局上下文,而声明中的 'this' 指的是函数?

Why does the 'this' in the prototype refer to the global context while the 'this' in the declaration refers to the function?

为什么原型中的this指的是全局上下文,而声明中的this指的是函数?即使试图显式设置 this 的上下文,它仍然指的是全局上下文。

var Foo = function (a) {
  console.log(this); // this will refer to global context
  this.bar = () => {
    // this refers to function context
    return a;
  };
};


Foo.prototype = {
  biz: () => {
    return this.bar(); // this this will refer to global context
  },
};

var f = new Foo(7);
f.biz(); // this.bar is not a function
f.biz.call(f); // this.bar is not a function

因为您将 biz 方法声明为 arrow function. You should generally not do that because an arrow function 声明 时保留 this (而不是 执行).

用这样的常规函数​​替换 biz

var Foo = function (a) {
  console.log(this); // this will refer to global context
  this.bar = () => {
    // this refers to function context
    return a;
  };
};


Foo.prototype = {
  biz() {
    return this.bar();
  },
};

var f = new Foo(7);
f.biz(); // Works
f.biz.call(f); // Works even if not needed