1

I just started with JS and I created a Contructor for a box. Now I want a box that can store Images and a box that can store text. How do I declare the new box objects, with prototype?

//box constructor

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

//image box features:

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

//text box features:

  this.font = ...
  this.font-size=...
  this.color=....
1
  • Box.prototype.src = ""; and etc... Commented Apr 6, 2013 at 22:42

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

6 Comments

Thank You, that was a fast answer @amNotIam, I check it out!
@vuvu: You're welcome. And I just changed it to use .call instead of .apply so that you pass individual arguments. I have a feeling that your TextBox and ImageBox constructors will be passed more args that don't need to be sent on.
How do I define a TextBox then, with 7 parameters or how would the syntax look like for a new TextBox? (Sorry, I'm new)
@vuvu: Just add additional parameters to the function after the existing ones. And then to make a new TextBox, just call the function with new before the call. var tb = new TextBox(0, 0, 100, 100, "foo-font", "12px", "maroon")
@amnotiam You can use apply and pass the arguments keyword (that is an array of the params received). this way is more flexible
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.