<分区>
方法一:
Rectangle.prototype.getArea = function() {
return this.length * this.width;
};
方法二:
Rectangle.prototype = {
getArea: function() {
return this.length * this.width;
}
};
上述每种方法的区别和优点是什么?
<分区>
方法一:
Rectangle.prototype.getArea = function() {
return this.length * this.width;
};
方法二:
Rectangle.prototype = {
getArea: function() {
return this.length * this.width;
}
};
上述每种方法的区别和优点是什么?
最佳答案
在第一种情况下,您要添加一个新属性到现有对象,在第二种情况下,您要覆盖 Rectangle.prototype
一个新值(对象)。
覆盖原型(prototype)会产生以下后果:
Rectangle.prototype.constructor
不再指向 Rectangle
。当您使用对象字面量时,它将指向 Object
。这可以通过分配
Rectangle.prototype.constructor = Rectangle;
您可能会丢失原型(prototype)上的所有现有属性(除非您再次添加它们,例如使用 constructor
)。
Rectangle
的现有实例不会受到更改的影响。它们仍会引用旧原型(prototype),不会继承新方法/属性。
instanceof
对现有 实例(即 rect instanceof Rectangle
)的测试将失败,因为 instanceof
比较原型(prototype),如前一点所述,现有实例保留对旧原型(prototype)的引用。
如果您在创建任何实例之前设置原型(prototype),那么您不必担心最后三点。
What are the differences and advantages of each of the methods above?
使用对象字面量重写原型(prototype)的唯一好处是语法更简洁。 IMO 它并没有超过缺点。
您可以通过合并两个对象来使用对象字面量而不覆盖原型(prototype):How can I merge properties of two JavaScript objects dynamically? .
关于javascript - 这些原型(prototype)声明有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16773061/
相关文章:
javascript - 使用javascript单击按钮后如何禁用特定表格行中的复选框?
javascript - 谷歌图片搜索鼠标悬停,它们是如何工作的?
javascript - 测试页面上是否存在 div 并将焦点设置为第一个
javascript - 如何为输入元素添加原型(prototype)?
javascript - 'this' 关键字在 Javascript 的对象原型(prototype)中返回窗口对象?
javascript - JavaScript 中特定时区的 new Date()
javascript - 中心图例不是所有图表,而是仅按绘图区域
python - 有没有办法为 Python 对象的所有成员打印简短版本的文档字符串?