为什么我们不能像这里这样绑定
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不是函数”。当然,我可以直接执行此操作,但是有时您需要子方法,并且我想了解其工作方式]
您的问题是,"Eva"
周围的引号不是标准引号。将其替换为正确的"
,然后重试。
function UserCreator(name, score) {
this.name = name;
this.score = score;
}
UserCreator.prototype.increment = function() {
function add1() {
console.log("test")
this.score++;
}
// const add1 = function(){this.score++;}
add1()
};
UserCreator.prototype.login = function() {
console.log("login");
};
const user1 = new UserCreator("Eva", 9)
user1.increment()
您的问题是,"Eva"
周围的引号不是标准引号。将其替换为正确的"
,然后重试。
function UserCreator(name, score) {
this.name = name;
this.score = score;
}
UserCreator.prototype.increment = function() {
function add1() {
console.log("test")
this.score++;
}
// const add1 = function(){this.score++;}
add1()
};
UserCreator.prototype.login = function() {
console.log("login");
};
const user1 = new UserCreator("Eva", 9)
user1.increment()