function userCreator(name,score){
const newUser = Object.create(userFunctions);
newUser.name = name;
newUser.score = score;
return newUser;
}
userFunctions = {
increment: function(){
this.score++;
}
};
userCreator.prototype.foo = function(){
console.log("foo");
};
const user1 = userCreator("Phil",5);
user1.foo();
我尝试向我的构造添加一个函数,但是当我添加这个函数并使用 user1
调用它时,它说 user1.foo()
不是一个函数。
最佳答案
看起来您希望对象原型(prototype)继承自 userFunctions
对象,在这种情况下你应该设置
userCreator.prototype = Object.create(userFunctions);
在构造函数之外。您还应该调用 new
在构造函数上,并且不要从中返回对象,以便 <functionName>.prototype
正常工作:
function userCreator(name,score){
this.name = name;
this.score = score;
}
userFunctions = {
increment: function(){
this.score++;
}
};
userCreator.prototype = Object.create(userFunctions);
userCreator.prototype.foo = function(){
console.log("foo");
};
const user1 = new userCreator("Phil",5);
user1.foo();
(从技术上讲,您可以使用 return this
,但这是多余的)
关于javascript - 新添加到构造函数原型(prototype)的函数在对象上调用时不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53247169/