我一直在摆弄 Javascript 原型(prototype),但我不明白为什么会这样:
function User(un) {
this.username = un;
}
User.prototype.method_name = function() {
return this.username;
};
var user = new User("Michael");
console.log(user.method_name());
但这不是:
function User(un) {
this.username = un;
return{
getUsername: function (){
return username;
},
setUsername: function(username) {
username = un;
}
};
}
User.prototype.method_name = function() {
return this.username;
};
var user = new User("Michael");
console.log(user.method_name());
为什么添加“return”语句会抛出 Object #<Object> has no method 'method_name'
?
最佳答案
因为在第二个例子中,你返回的对象不是一个新的“用户”实例,而是一个普通的对象实例。
当你对构造函数使用new关键字时,默认返回的对象继承自构造函数的原型(prototype),所以你有一个继承链如下:
user -> User.prototype -> Object.prototype -> null
如果你返回一些其他对象,它不会从构造函数继承,你有一个继承链,如:
user -> Object.prototype -> null
关于javascript - 无法将方法原型(prototype)添加到 JavaScript 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19720600/