如何向“新”实例添加属性?

时间:2011-08-02 21:05:30

标签: javascript oop

如何向new function的实例添加属性?

例如:

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

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

调用s.height时,我得到一个未定义的结果。如何正确执行此操作?

4 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:2)

这是一个语法错误。 new Constructor()调用后面不应该有大括号,新实例应该直接引用。此外,构造函数定义需要function关键字

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

var s = new Constructor() 

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

答案 2 :(得分:2)

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

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

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

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

答案 3 :(得分:2)

这实际上取决于你想要做什么。

如果在您的示例sConstructor是唯一具有属性height的{​​{1}}实例,那么请执行以下操作:

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

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

如果要将height属性添加到Constructor的所有实例,请执行以下操作:

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

Constructor.prototype.height = 30px;

var s = new Constructor();

如果你想要一个具有高度的新Constructor能够被实例化,那就这样做:

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

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

ConstuctorWithHeight.prototype = new Constructor();

var s = new ConstuctorWithHeight();