Jon Doe
Jon Doe

Reputation: 751

Adding members to an existing object

Suppose we have the following object:

var obj = {
    fn1: function() {
    }
}

how can I dynamically add another member to it, say

fn2: function() {}

Upvotes: 26

Views: 47618

Answers (5)

Ghafoor
Ghafoor

Reputation: 458

var obj = { };

// Adding function by extending the object using dot notation

obj.subtract = function(num1,num2){
    return num1 - num2;
};

console.log(obj.subtract(8,5));//3

//Adding function by extending the object using bracket notation

obj['multiply them'] = function(num1,num2){

    return num1 * num2 ;

};

console.log(obj[' multiply them '](3,3)); // 9

Upvotes: 2

Phrogz
Phrogz

Reputation: 303244

As others have pointed out:

obj.fn2 = function(){ ... };

Note that if "fn2" is not a valid identifier, you must instead use the 'array' notation for the object:

obj["fn2"] = function(){ ... };
obj["!! crazy-names#allowed?!"] = function(){ ... };

This is also how you would do it if you had the name of the property stored in a variable:

var propName = "fn2";
obj[propName] = function(){ ... };

If you want to test if a property exists for an object, you can use the in operator:

if ("fn2" in obj){ ... }

If you want to remove a property from an object, use the delete keyword:

var o = { a:42 };
console.log( "a" in o ); // true
delete o.a;              // Or delete o["a"]
console.log( "a" in o ); // false

To iterate over all properties in an object, use the in operator in a for loop. Be sure to var the variable so that it isn't global:

var o = { a:42, b:17 };
var allPropertyNames  = [];
var allPropertyValues = [];
for (var propName in o){
  // If you don't do this test, propName might be a property inherited
  // by this object, and not a property on the object itself.
  if (o.hasOwnProperty(propName)){
    allPropertyNames.push(propName);
    allPropertyValues.push(o[propName]);
  }
}
console.log( allPropertyNames );  // [ "a", "z" ]
console.log( allPropertyValues ); // [ 42, 17 ]

Upvotes: 52

Jimmy Chandra
Jimmy Chandra

Reputation: 6580

you can use prototype for that...

obj.prototype.fn2 = function() {
 ....
}

or just simply

obj.fn2 = function() {
 ....
}

Upvotes: -1

ChaosPandion
ChaosPandion

Reputation: 78262

It's quite simple actually:

obj.fn2 = function() { }

Upvotes: 7

eHussain
eHussain

Reputation: 3367

Try out following

var obj = {
   fn1: function() {
   } 
}

obj.fn2 = function() {} // this will add another member to existing object

Hope this will help.

Thanks!

Hussain.

Upvotes: 6

Related Questions