2013-04-06 59 views
1

我剛剛開始使用JS,併爲框創建了一個構造函數。現在我想要一個可以存儲圖像的盒子和一個可以存儲文本的盒子。如何用原型聲明新的盒子對象?JS原型,創建具有新功能的對象

//盒構造

function Box(x, y, w, h) { 
    this.x = x; 
    this.y = y; 
    this.w= w; 
    this.h= h;  
} 

//圖像盒的特點:

this.src = .... 
this.title = ... 

//文本框的特點:

this.font = ... 
    this.font-size=... 
    this.color=.... 
+0

Box.prototype.src = 「」;等... – Givi 2013-04-06 22:42:26

回答

5
function Box(x, y, w, h) { 
    this.x = x; 
    this.y = y; 
    this.w = w; 
    this.h = h;  
} 

function ImageBox(x, y, w, h) { 
    Box.call(this, x, y, w, h); // Apply Box function logic to new ImageBox object 

    this.src = .... 
    this.title = ... 
} 
// Make all ImageBox object inherit from an instance of Box 
ImageBox.prototype = Object.create(Box.prototype); 

function TextBox(x, y, w, h) { 
    Box.call(this, x, y, w, h); // Apply Box function logic to new TextBox object 

    this.font = ... 
    this.font-size =... 
    this.color =.... 
} 
// Make all TextBox object inherit from an instance of Box 
TextBox.prototype = Object.create(Box.prototype); 
+0

謝謝你,這是一個快速的答案@amNotIam,我看看! – vuvu 2013-04-06 22:44:07

+0

@vuvu:不客氣。我只是改變它使用'.call'而不是'.apply',以便傳遞單獨的參數。我有一種感覺,你的'TextBox'和'ImageBox'構造函數會傳遞更多不需要發送的參數。 – 2013-04-06 22:48:26

+0

那麼如何定義一個TextBox,然後使用7個參數,或者對於一個新的TextBox,語法看起來如何? (對不起,我是新手) – vuvu 2013-04-06 22:58:06