如何向new function
的实例添加属性?
例如:
function Constructor() {
this.color = "red";
}
var s = new Constructor() {
this.color = "blue";
this.height = 30px;
}
调用s.height
时,我得到一个未定义的结果。如何正确执行此操作?
答案 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)
这实际上取决于你想要做什么。
如果在您的示例s
中Constructor
是唯一具有属性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();