开发者

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 prope开发者_开发百科rly?


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");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜