Navin Rauniyar
Navin Rauniyar

Reputation: 10525

How to create new property and value for a function?

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.

Upvotes: 0

Views: 77

Answers (4)

aaron-bond
aaron-bond

Reputation: 3341

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.

Upvotes: 0

Shomz
Shomz

Reputation: 37701

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.

Upvotes: 2

pgolm
pgolm

Reputation: 46

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' })

Upvotes: 0

Linga
Linga

Reputation: 10553

Try something like this

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

Upvotes: 0

Related Questions