Javascript 这些原型声明之间有什么区别?
方法1:Javascript 这些原型声明之间有什么区别?,javascript,oop,prototype,Javascript,Oop,Prototype,方法1: Rectangle.prototype.getArea = function() { return this.length * this.width; }; Rectangle.prototype = { getArea: function() { return this.length * this.width; } }; 方法2: Rectangle.prototype.getArea = function() { re
Rectangle.prototype.getArea = function() {
return this.length * this.width;
};
Rectangle.prototype = {
getArea: function() {
return this.length * this.width;
}
};
方法2:
Rectangle.prototype.getArea = function() {
return this.length * this.width;
};
Rectangle.prototype = {
getArea: function() {
return this.length * this.width;
}
};
上述每种方法的区别和优点是什么?第二种方法打破了继承链,并删除了您之前添加到原型中的所有属性 让我们通过这个例子来了解我所说的“继承链断裂”是什么意思:
function A(){}
A.prototype.a = function(){}
function B(){}
B.prototype = new A();
B.prototype.b = function(){}
这里的B
实例继承了a
方法
但如果你这样做了
B.prototype = { b: function(){} }
如果
Rectangle.prototype
是{}
,这两种方法之间没有区别。在第一种情况下,您将向现有对象添加一个新属性,在第二种情况下,您将用一个新值覆盖Rectangle.prototype
(对象)
覆盖原型会产生以下后果:
不再指向Rectangle.prototype.constructor
。当您使用对象文字时,它将指向Rectangle
。通过指定object
Rectangle.prototype.constructor = Rectangle;
- 您可能会丢失原型上的所有现有属性(除非您再次添加它们,如使用
)构造函数
- 现有的矩形实例不会受到更改的影响。它们仍将引用旧原型,不会继承新方法/属性
对现有的实例(即instanceof
)的测试将失败,因为rect instanceof Rectangle
比较原型,如前一点所述,现有实例保留对旧原型的引用instanceof
通过合并两个对象,您可以使用对象文字而不覆盖原型:。与使用普通对象时相同,第二种样式将销毁
prototype
的所有现有内容。这与x+=10
vsx=10
基本相同。另请参阅,谢谢!现在它更有意义了感谢您提供的详细信息我解释过了,明白了!