Skip to content Skip to sidebar Skip to footer

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 Objec

Solution 1:

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() {returnthis.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.

Solution 2:

Try something like this

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

Solution 3:

You can merge two object like:

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

var v = newMyObject(1, { value2: '2' })

Solution 4:

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.

Post a Comment for "How To Create New Property And Value For A Function?"