2013-04-25 23 views
1

所有,如果我傳遞一個對象到Object.create,這意味着創建一個新的對象從它繼承。下面的代碼證明了它。Object.create從一個對象

 function Shape() { 
      this.x = 0; 
      this.y = 0; 
     } 

     Shape.prototype.move = function(x, y) { 
      this.x += x; 
      this.y += y; 
      console.info("Shape moved."); 
     }; 

     Rectangle = Object.create(Shape); 
     Rectangle.__proto__==Shape;//it is true.yes, I can understand 
     Rectangle//It is Function {} I can not understand it. 
     Rectangle.constructor==Function//it is true.I can not understand it. 

該圖表示關係如下。但是我不明白的是它的亮點部分。究竟是什麼Rectangle?我的意思是什麼Function{},它來自哪裏?以及Rectangle.constructor屬性,我不知道所有對象是否具有constructor屬性,以及constructor屬性用於什麼目的?謝謝。

PS:以上所有值都是在FireBug中計算和觀察的。

enter image description here

更正圖由MiniTech移動的評論

enter image description here

回答

2

那怎麼使用Object.create作品繼承現在。它應該是這個樣子:

function Shape() { 
    this.x = 0; 
    this.y = 0; 
} 

Shape.prototype.move = function(x, y) { 
    this.x += x; 
    this.y += y; 
    console.info("Shape moved."); 
}; 

function Rectangle() { 
    Shape.call(this); 
} 

Rectangle.prototype = Object.create(Shape.prototype); // Leaving out the constructor business for simplicity 

你在做什麼有重複的實際Shape功能,所以當然(是一個函數)它的構造是Function

P.S. Rectangle.__proto__ = Shape不是比較。

+0

+1 - +2更多,當你添加一些關於構造函數的信息和它的作用;-) – 2013-04-25 02:21:40

+1

@SeanVieira:哪個構造函數? '函數'或'矩形'或'矩形'的排序?「? :D – Ryan 2013-04-25 02:22:40

+0

大家好,很抱歉再錯過一次'=',應該是'==',請再次查看。謝謝。 – 2013-04-25 02:24:11