无法将方法原型添加到JavaScript对象

时间:2013-11-01 04:03:36

标签: javascript

我正在搞乱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'

2 个答案:

答案 0 :(得分:4)

因为在第二个示例中,您返回的对象不是新的“User”实例,而是一个普通的Object实例。

当你将 new 关键字与构造函数一起使用时,默认返回的对象继承自构造函数的 prototype ,因此你有一个继承链,如:

user -> User.prototype -> Object.prototype -> null

如果你返回一些其他对象,它不会从构造函数继承而且你有一个继承链,如:

user -> Object.prototype -> null

答案 1 :(得分:3)

返回一个对象会绕过构造函数的常规返回值,即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;
};