4
<script>
function User (theName, theEmail) {
    this.name = theName;
    this.email = theEmail;
}

User.prototype = {
    constructor: User,
    changeEmail:function (newEmail)  {
        this.email = newEmail;
        return "New Email Saved: " + this.email;
    }
}
// A User 
firstUser = new User("Richard", "Richard@examnple.com"); 
firstUser.changeEmail("RichardB@examnple.com");
</script>

这段代码取自这里:http: //javascriptissexy.com/oop-in-javascript-what-you-need-to-know/

问题:

把这条线放在上面是不是很重要:constructor: User,?如果我删除了这条线,它仍然有效。

4

2 回答 2

2

当我们在 javascript 中使用new操作符或创建新对象时{},新创建的对象的构造函数属性指向构造函数。在你的情况下:

firstUser = new User("Richard", "Richard@examnple.com"); 

firstUser.constructorUser。这同样适用于您的User.prototype. 当你用{}来创建一个新对象时User.prototype,构造函数的属性是Object。当您放置时constructor: User,您只需将构造函数属性从更改ObjectUser,您的代码仍然有效。

于 2013-06-18T04:21:42.493 回答
0

如果你用一个新对象替换默认原型,你只需要这样做,就像你对User.prototype = {...}. 您可以改为扩展默认原型:

User.prototype.changeEmail = function (newEmail)  {
   this.email = newEmail;
   return "New Email Saved: " + this.email;
}
于 2013-06-18T04:37:58.497 回答