[英]javascript Object.create()
function Shape() {}
Shape.prototype.move = function(x, y) {
console.info('Shape moved.');
};
function Rectangle() {
Shape.call(this);
}
Rectangle.prototype = Object.create(Shape.prototype);
console.log('Is rect an instance of Rectangle?', rect instanceof Rectangle);// true
console.log('Is rect an instance of Shape?', rect instanceof Shape);// true
rect.move(1, 1); // Outputs, 'Shape moved.'
我在 MDN 上遇到過這個例子。 我可以知道是否有重大變化來替換Rectangle.prototype = Object.create(Shape.prototype);
with Rectangle.prototype = Shape.prototype;
? 兩種情況下的結果相同。 有人告訴我原型屬性本身就是一個對象,那么為什么我們要先使用 object.create() 創建另一個對象,然后再將它分配給矩形的屬性呢? 為什么不直接將形狀的原型分配給矩形?
讓我們擴展您的示例以查看差異。
function Shape() {}
Shape.prototype.move = function(x, y) {
console.info('Shape moved.');
};
function Rectangle() {
Shape.call(this);
}
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.move = function(x, y) {
console.info('Rectangle moved.');
};
var shape = new Shape();
var rect = new Rectangle();
console.log('Is rect an instance of Rectangle?', rect instanceof Rectangle);// true
console.log('Is rect an instance of Shape?', rect instanceof Shape);// true
shape.move(1, 1); // 'Shape moved.'
rect.move(1, 1); // 'Rectangle moved.'
現在讓我們看看當你不使用Object.create()
時會發生什么:
function Shape() {}
Shape.prototype.move = function(x, y) {
console.info('Shape moved.');
};
function Rectangle() {
Shape.call(this);
}
Rectangle.prototype = Shape.prototype;
Rectangle.prototype.move = function(x, y) {
console.info('Rectangle moved.');
};
var shape = new Shape();
var rect = new Rectangle();
console.log('Is rect an instance of Rectangle?', rect instanceof Rectangle);// true
console.log('Is rect an instance of Shape?', rect instanceof Shape);// true
shape.move(1, 1); // 'Rectangle moved.'
rect.move(1, 1); // 'Rectangle moved.'
當您不使用Object.create()
創建基於Shape.prototype
對象的新原型時,您只需分配對現有原型的引用,然后當您覆蓋Rectangle
的一些原型方法時,您就實際上也覆蓋了Shape
的原型方法,因為它是同一個對象。
如果你使用
Rectangle.prototype = Shape.prototype;
Rectangle和Shape原型都是同一個對象,你添加到Rectangle 的每個方法/屬性也會出現在Shape 中。
這種方法Rectangle.prototype = Object.create(Shape.prototype);
將確保Shape.prototype
由Rectangle
繼承( Shape.prototype
)基本功能。 這防止Shape.prototype
修改由Rectangle.prototype
。
考慮以下:
...
Rectangle.prototype = Shape.prototype; // Shape.prototype is assigned as reference
var rect = new Rectangle();
Rectangle.prototype.add = "add method";
console.log(JSON.stringify(Shape.prototype,0,4));
...
// the output will be like(Shape.prototype was changed):
{
"add": "add method"
}
如您所見,將Shape.prototype
直接分配給Rectangle.prototype
作為引用允許Rectangle.prototype
修改Shape.prototype
。
而Object.create(Shape.prototype)
將被分配為新的“獨立”對象(所有Rectangle.prototype
擴展都不會影響Shape.prototype
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.