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;
};
各位麻烦帮我解答下,不是很懂..谢谢
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
如果使用
new操作符实例化第一个MyObject的时候会把constructor属性设为MyObject,而你使用了对象字面量来重写了原型,constructor值就不存在了。第二个则没有这个问题。
推荐使用第二种方法,或者在第一种方法上重新把
constructor属性指向MyObject。第一种:
第二种:
补充一下,可以先去了解js的原型链,第一种不是
constructor不存在了,而是把内置的[[prototype]]指向了Object.prototype,所以第一种的constructor变成了Object,第二种维持了MyObject区别不是很大,第一种更省代码。可以加一个属性constructor,指向构造函数自身