function MyObject(name, message) {
this.name = name.toString();
this.message = message.toString();
}
MyObject.prototype = {
getName: function() {
return this.name;
},
getMessage: function() {
return this.message;
}
};
和
function MyObject(name, message) {
this.name = name.toString();
this.message = message.toString();
}
MyObject.prototype.getName = function() {
return this.name;
};
MyObject.prototype.getMessage = function() {
return this.message;
};
代码中的下面2段有什么区别?哪种写法比较好一些?
MyObject.prototype = {
getName: function() {
return this.name;
},
getMessage: function() {
return this.message;
}
};
和
MyObject.prototype.getName = function() {
return this.name;
};
MyObject.prototype.getMessage = function() {
return this.message;
};
各位麻烦帮我解答下,不是很懂..谢谢
如果使用
new
操作符实例化第一个MyObject
的时候会把constructor
属性设为MyObject
,而你使用了对象字面量来重写了原型,constructor
值就不存在了。第二个则没有这个问题。
推荐使用第二种方法,或者在第一种方法上重新把
constructor
属性指向MyObject
。