Javascript 为什么在这种情况下在原型继承中使用Object.create()?
考虑以下代码:-Javascript 为什么在这种情况下在原型继承中使用Object.create()?,javascript,prototypal-inheritance,Javascript,Prototypal Inheritance,考虑以下代码:- function Rectangle(length, width) { this.length = length; this.width = width; } Rectangle.prototype.getArea = function() { return this.length * this.width; }; function Square(size) { Rectangle.call(this, size, size); } S
function Rectangle(length, width) {
this.length = length;
this.width = width;
}
Rectangle.prototype.getArea = function() {
return this.length * this.width;
};
function Square(size) {
Rectangle.call(this, size, size);
}
Square.prototype = Object.create(Rectangle.prototype);
var rect = new Rectangle(5, 5);
var square = new Square(7);
console.log(rect.getArea()); // 25
console.log(square.getArea()); // 49
我们为什么要这样做继承:-
Square.prototype = Object.create(Rectangle.prototype);
而不是这样:-
Square.prototype = Rectangle.prototype;
它们似乎都完成了所需的任务。设置
Square.prototype=Rectangle.prototype
意味着它们都是同一个对象,这几乎肯定不是您想要的。正方形是矩形,但矩形不是正方形,因此行为将不同。您需要两个不同的原型对象
使用Object.create()
是一种干净的方法,可以创建一个具有给定对象(在本例中为Rectangle.prototype
)作为其原型链头的对象。结果是,Square.prototype
是一个独特的对象,可以赋予它自己的属性(适用于正方形而不是矩形的特殊方法),但它也可以访问矩形原型中的方法
因此,当您通过
new Square(100)
创建一个正方形时,您会得到一个对象,其直接原型是使用object.create()
创建的对象,并且(大概)装饰有各种有趣的正方形行为。该对象依次将矩形.prototype
作为其原型链中的第一项。这样做的效果是,如果调用,比如说,mysquare.area()
,并且在矩形原型上定义了area()
,则查找将从方形实例继续到方形原型,然后到将找到该方法的矩形原型。Object.create在目标原型的顶部添加另一个对象。这意味着您可以在不修改原始原型的情况下设置此对象的属性。@TJCrowder在某些地方有一篇关于为什么使用对象的优秀文章。create()
比使用new
好得多。明白了,这真的很有帮助!非常感谢。