[英]Can't add method prototype to JavaScript object
我在弄亂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'
?
因為在第二個示例中,您返回的對象不是新的“ User”實例,而是普通的Object實例。
當您將新關鍵字與構造函數一起使用時,默認情況下返回的對象將從構造函數的prototype繼承,因此您具有如下的繼承鏈:
user -> User.prototype -> Object.prototype -> null
如果返回其他對象,則該對象不會從構造函數繼承,並且您將具有如下的繼承鏈:
user -> Object.prototype -> null
返回對象可以避免構造函數的通常返回值,即this
變量。 而不是返回this
,而是返回其他對象,並且該對象沒有username屬性或method_name方法。 這大致發生在代碼的每個點:
function User(un) {
this.username = un; // puts username on the 'this' object
// returns an entirely different, unrelated object that doesn't use User's prototype
return{
getUsername: function (){
return un;
},
setUsername: function(username) {
un = username;
}
};
}
// sets method_name on the prototype of the 'this' object for User
User.prototype.method_name = function() {
return this.username;
};
var user = new User("Michael"); // passes a new User.prototype as the implicit 'this' in the User function
console.log(user.method_name());
相反,請嘗試以下操作:
function User(un) {
this.username = un;
this.getUsername = function (){
return un;
};
this.setUsername = function(username) {
un = username;
};
}
User.prototype.method_name = function() {
return this.username;
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.