簡體   English   中英

在JavaScript中使用protypal inheritence分配簡單原型和使用Object.Create(Object.prototype)之間的差異?

[英]Diffrence between assigning simple prototype and using Object.Create(Object.prototype) in protypal inheritence in JavaScript?

我正在使用簡單的原型分配在java腳本中實現Prototypal inheritence這是我的代碼 -

var Rectangle = function(heigth, width) {
  this.height = height;
  this.width  = width;  
}

Rectangle.prototype.area = function() {
  return this.height*this.width;
}

var Square = function(length) {
  this.height = this.width = length;
}

Square.prototype = Rectangle.prototype; 

var sqr1 = new Square(5);
console.log(sqr1.area());

但是在Square.prototype = Rectangle.prototype的位置,建議使用Square.prototype = Object.create(Rectangle.prototype) 任何人都可以告訴我潛在的差異,因為上面的代碼工作正常。

因為語句Square.prototype = Rectangle.prototype; 實際上復制Rectangle.prototype的引用並將其分配給Square.prototype (原始類型按值復制,引用類型通過引用復制)。

因此,如果您要在Square.prototype上添加一些屬性和方法,它將修改原始的Rectangle.prototype對象,這不是您想要的。

Square.prototype = Object.create(Rectangle.prototype)創建一個新object其原型是Rectangle.prototype ,這是正確的方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM