问题描述:

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?

网友答案:
function Constructor() {
   this.color = "red";
}

var s = new Constructor();
s.color = "blue";
s.height = 30px;
网友答案:

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;
网友答案:

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();
网友答案:
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");
相关阅读:
Top