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

时间:2021-08-01 18:05:03

标签: javascript this

为什么原型中的 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

1 个答案:

答案 0 :(得分:1)

因为您将 biz 方法声明为 arrow function。您通常不应该这样做,因为 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