我在搞乱 Javascript 原型,但我不明白为什么会这样:
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'
?