2013-04-06 34 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