functionMyObject(name,message){this.name=name.toString();this.message=message.toString();}MyObject.prototype={getName:function(){returnthis.name;},getMessage:function(){returnthis.message;}};和functionMyObject(name,message){this.name=name.toString();this.message=message.toString();}MyObject.prototype.getName=function(){returnthis.name;};MyObject.prototype.getMessage=function(){returnthis.message;};代码中的下面2段有什么区别?哪种写法比较好一些?MyObject.prototype={getName:function(){returnthis.name;},getMessage:function(){returnthis.message;}};和MyObject.prototype.getName=function(){returnthis.name;};MyObject.prototype.getMessage=function(){returnthis.message;};各位麻烦帮我解答下,不是很懂..谢谢
2 回答

精慕HU
TA贡献1845条经验 获得超8个赞
如果使用new操作符实例化第一个MyObject的时候会把constructor属性设为MyObject,而你使用了对象字面量来重写了原型,constructor值就不存在了。第二个则没有这个问题。推荐使用第二种方法,或者在第一种方法上重新把constructor属性指向MyObject。

慕桂英4014372
TA贡献1871条经验 获得超13个赞
第一种:构造函数MyObject原来指向了空的原型对象,后来你将它又指向了新的原型对象。第二种:构造函数MyObject原来指向了空的原型对象,后又为其原有的原型对象对象添加了两个方法。
添加回答
举报
0/150
提交
取消