0
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'); 

Okay, now how can I create new property and value for the Person something like this:

var codyC = new Person(true, 33, 'male','children:true');

I mean to add new property for the Person.

Navin Rauniyar
  • 10,127
  • 14
  • 45
  • 68

4 Answers4

2

You can send an object of additional properties as a fourth parameter. Like this:

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
    }
};

And then instantiate it like this

var codyB = new Person(true, 33, 'male', {children: true, somethingElse: "etc..."}); 

You can use just this one parameter to specify all of the Person properties, if it works for you.

Tobias
  • 7,723
  • 1
  • 27
  • 44
Shomz
  • 37,421
  • 4
  • 57
  • 85
  • You're welcome. There are many ways to do it, but this one seemed the most straightforward and flexible one. – Shomz Jan 29 '14 at 12:08
  • Well, look at the other answers for some ideas. Then, you can also have some kind of a whitelist for possible additional properties. It really depends what you need - the list could go on and on. – Shomz Jan 29 '14 at 12:09
  • @NavinRauniyar You should really consider replacing all of your parameters with an object instead of just the "Optional" one at the end as shown above. It will benefit you in the long run. See my answer for more details. – aaron-bond Jan 29 '14 at 12:56
0

Consider using a config object instead of parameters to a function. More information here: Javascript: Configuration Pattern

Doing so will allow you to set defaults for properties and set whichever ones you want at construction instead of making a lot of parameters to your constructor.

Person({
  "living" : true,
  "age": 30
});

Then you could default your other properties so that you don't have to set them every time. This makes your code much more readable too.

Community
  • 1
  • 1
aaron-bond
  • 3,101
  • 3
  • 24
  • 41
0

Try something like this

var codyC = new Person(true, 33, 'male');
codyC.children = true;
Linga
  • 10,379
  • 10
  • 52
  • 104
0

You can merge two object like:

var MyObject = function(value, properties) { 
    this.value = value; 
    for (var attrname in properties) {
        this[attrname] = properties[attrname];
    } 
}

var v = new MyObject(1, { value2: '2' })
pgolm
  • 46
  • 1
  • 4