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添加新属性。

最佳答案

您可以发送具有其他属性的对象作为第四个参数。像这样:

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属性(如果适用)。

关于javascript - 如何为函数创建新的属性和值?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21430371/

10-13 00:44