首页 > 解决方案 > this.add1 不是函数

问题描述

为什么我们不能像这里一样绑定它

function UserCreator(name, score) {
  this.name = name;
  this.score = score;
}

UserCreator.prototype.increment = function () {
  function add1() {
    this.score++;
  }

  this.add1()
};

UserCreator.prototype.login = function () {
  console.log("login");
};

const user1 = new UserCreator("Eva", 9)
user1.increment()

返回“this.add1 不是函数”。当然,我可以直接做,但有时你需要子方法,我想了解它是如何工作的

标签: javascriptfunctionthis

解决方案


所以本质上它正在运行window.add1(),如果使用 add1() 调用它,它将运行window.score++返回一个 NaN。需要研究我的“这个”概念。


推荐阅读