1

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

4

2 回答 2

4

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

当你在构造函数中使用new关键字时,默认返回的对象继承自构造函数的原型,所以你有一个继承链,如:

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

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

user -> Object.prototype -> null
于 2013-11-01T04:06:01.133 回答
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;
};
于 2013-11-01T04:09:55.583 回答