如何将属性添加到";新的";例如

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

本文关键字:quot 新的 例如 属性 添加      更新时间:2023-09-26

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

例如:

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

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

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

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

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

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

如果在您的示例中,sConstructor的唯一具有属性height的实例,则执行以下操作:

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