dopatraman
dopatraman

Reputation: 13908

How do I add properties to a "new" instance?

How do I add properties to an instance of a new function?

For example:

function Constructor() {
    this.color = "red";
}

var s = new Constructor() {
    this.color = "blue";
    this.height = 30px;
}

When s.height is invoked, I am getting an undefined result. How does one execute this properly?

Upvotes: 2

Views: 126

Answers (4)

Ilia Choly
Ilia Choly

Reputation: 18557

function Constructor(options){
    for(var key in options){
        this[key] = options[key];
    }
}

var s = new Constuctor({color: "red",height: "30px"});

or

function Constructor(color,height){
    this.color = color;
    this.height = height;
}

var s = new Constuctor("red","30px");

Upvotes: 2

Utilitron
Utilitron

Reputation: 402

It really depends on what you are trying to do.

If in your example s is the only instance of Constructor that will have the property height, then do it like this:

function Constructor() {
  this.color = "red";
}

var s = new Constructor() 
s.height = 30px;

if you want to add the height property to all instances of Constructor then do it like this:

function Constructor() {
  this.color = "red";
}

Constructor.prototype.height = 30px;

var s = new Constructor();

if you want a new Constructor with height to be able to be instantiated then do it like this:

function Constructor() {
  this.color = "red";
}

function ConstuctorWithHeight(){
  this.height = 30px;
}

ConstuctorWithHeight.prototype = new Constructor();

var s = new ConstuctorWithHeight();

Upvotes: 2

Andrew
Andrew

Reputation: 13853

function Constructor() {
   this.color = "red";
}

var s = new Constructor();
s.color = "blue";
s.height = 30px;

Upvotes: 3

Richard Hoffman
Richard Hoffman

Reputation: 729

That's a syntax error. The new Constructor() call shouldn't be followed by braces, and the new instance should be referenced directly. also, the constructor definition needs the function keyword

function Constructor() {
  this.color = "red";
}

var s = new Constructor() 

s.color = "blue";
s.height = 30px;

Upvotes: 3

Related Questions