var Person = function(living, age, gender) {
this.living = living;
this.age = age;
this.gender = gender;
this.getGender = function() {return this.gender;};
};
// logs Object {living=true, age=33, gender="male", ...}
var codyB = new Person(true, 33, 'male');
好的,现在我怎样才能为Person创建新的属性和值:
var codyC = new Person(true, 33, 'male','children:true');
我的意思是为Person添加新属性。
答案 0 :(得分:2)
您可以将附加属性的对象作为第四个参数发送。像这样:
var Person = function(living, age, gender, additional) {
this.living = living;
this.age = age;
this.gender = gender;
this.getGender = function() {return this.gender;};
for (var p in additional) {
this[p] = additional[p];
// do more mods here
}
};
然后像这样实例化
var codyB = new Person(true, 33, 'male', {children: true, somethingElse: "etc..."});
如果它适用于您,您可以只使用这一个参数来指定所有Person属性。
答案 1 :(得分:0)
考虑使用配置对象而不是函数的参数。更多信息: Javascript: Configuration Pattern
这样做可以让你设置属性的默认值,并在构造时设置你想要的那些,而不是为你的构造函数制作很多参数。
Person({
"living" : true,
"age": 30
});
然后您可以默认其他属性,这样您就不必每次都设置它们。这使您的代码更具可读性。
答案 2 :(得分:0)
尝试这样的事情
var codyC = new Person(true, 33, 'male');
codyC.children = true;
答案 3 :(得分:0)
您可以合并两个对象,如:
var MyObject = function(value, properties) {
this.value = value;
for (var attrname in properties) {
this[attrname] = properties[attrname];
}
}
var v = new MyObject(1, { value2: '2' })