A Function for Adding Properties to an Object Literal
Earlier in the Object Literals Tutorial we provided information on how to Add, Modify, and Access Properties of a JavaScript object literal. As we mentioned there, if you have a number of properties to add to an object, it can be helpful to have a function to do this for you. We present such a function here.
Starting with the following object literal:
var Object1 = {
propA: 'some string value',
propB: true
};
Suppose the following is an object literal whose properties you want to add to Object1
:
var Object2 = {
propC: 'Another property',
propD: 'Me too!'
}
The augment
function below provides the means to do so:
// add properties of Obj2 to Obj1
function augment(Obj1, Obj2) {
var prop;
for ( prop in Obj2 ) {
if ( Obj2.hasOwnProperty(prop) && !Obj1[prop] ) {
Obj1[prop] = Obj2[prop];
}
}
}
In the call to the augment
function, the first argument is the object to which you want to add the second argument's properties:
augment(Object1, Object2);
// to verify Object2.propC is now in Object1 too
console.log(Object1.propC); // Another property
Since one purpose of object literals is to minimize impact on the global namespace, if the augment
function is included as a method of an object or class in your library, you can enclose your new properties in an immediate function[1] and call the augment method without any additional impact on the global namespace.
(function(){
// props to add to myObject
var Obj = {
propA: 'Another property',
propB: 'Me too!'
};
// if augment is method of myLib object
myLib.augment(Object1, Obj);
}()); // invoke immediately
- An immediate function is invoked as soon as it is defined. See more information at JSPatterns.com. ^