user1032531
user1032531

Reputation: 26281

Adding methods to an JavaScript object

I could create an object with some methods, and later add a property to it as follows:

var myObj = (function () {
    var my = {};
    my.method1=function(){}
    my.method2=function(){}
    my.method3=function(){}
    return my;
    }());
myObj.myProperty=123;

How could I create the object first and add a property, and then later add the methods afterwards?

myObj={};
myObj.myProperty=123;
//How do I add the above methods to myObj?

Upvotes: 0

Views: 47

Answers (3)

roshan
roshan

Reputation: 2510

Even prototype can add the functions to original object.

 var myObj = function() {
   this.myProperty = 123;
 }

 myObj.prototype.method1 = function method1() {
   alert("method1")
 }
 myObj.prototype.method2 = function method2() {
   alert("method2")
 }
 var newObj = new myObj();
 newObj.method1();
 newObj.method2();
 console.log(newObj)

Upvotes: 0

konkked
konkked

Reputation: 3231

You can do an extend operation using an existing object

var myObj = {...}

var myAdditionalMethods = { someMethod : function(){ } }

//extend the object
for(var i in myAdditionalMethods)
   if(!myObj.hasOwnProperty(i)) 
       myObj[i] = myAdditionalMethods[i];

there are a lot of libraries that have this functionality built in, but that is how you would do it without one

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816334

I guess there are two solutions:

Merge the objects:

var myObj = {...};
// ...
var objWithMethods = (function() { ... }());
Object.assign(myObj, objWithMethods);

(Object.assign is an ES6 methods. A polyfill can be found in the link, libraries often also provide a method with similar behavior).

Pass the object the methods should be assigned to as argument:

var myObj = {};
myObj = (function (obj) {
    var my = obj || {};
    my.method1=function(){}
    my.method2=function(){}
    my.method3=function(){}
    return my;
}(myObj));

Upvotes: 1

Related Questions