"this" 内部原型采用 window 而不是对象

"this" inside prototype takes window instead of object

我创建了一个名为 Survey 的对象并向其添加了一个原型函数,当我在原型函数中进行控制台记录时,日志显示 window 对象而不是父 Survey 对象。

function Survey(questions = []) {
  this.__questions__ = questions;
};
Survey.prototype.testFunction = () => {
  console.log(this);
  return this.__questions__;
}
// Create your object here
const SUR = new Survey(['1','2']);

SUR.testFunction(); // this prints [[Window]] Object instead of Survey

预期结果将是调查对象

因为你使用了Arrow function。 在箭头函数中,this 将引用外部。只需使用普通函数即可。

Survey.prototype.testFunction = function() {
  console.log(this);
  return this.__questions__;
}

问题就到这里:

Survey.prototype.testFunction = () => {}

箭头函数没有 this-context,它将使用方法外部的 this-context。由于没有定义其他 this-context,它将是 window 对象。

修复非常简单:使用常规函数:

Survey.prototype.testFunction = function () {}