morishi
morishi

Reputation: 43

Extending javascript object

I already have this:

var myVar = { appName: 'Test' };

I want to add this:

myVar = {
         exec: function()
             {
                console.log('do stuff');  
             } 
         }

And have this:

   myVar = {
               appName: 'Test',
               exec: function()
               {
                 console.log('do stuff');  
               } 
           }

Actually, I want to be able to access myVar.appName and myVar.exec();

So, I can:

myVar.exec = function(){};

But if I have many more functions and variables.

Do I have to keep doing this:

myVar.func1 = function(){ // stuff 1 };
myVar.func2 = function(){ // stuff 2 };
myVar.func3 = function(){ // stuff 3 };

Are there a better way?

Upvotes: 1

Views: 168

Answers (5)

Reid Rankin
Reid Rankin

Reputation: 1129

You're looking for Object.assign()!

var myVar = { appName: 'Test' };
Object.assign(myVar, {
    exec: function(){
        console.log('do stuff');  
    }
    exec2: function(){
        console.log('do other stuff');  
    }
});

You can then access myVar.appName, myVar.exec, and myVar.exec2.

Upvotes: 0

ron tornambe
ron tornambe

Reputation: 10780

All you need to do is set the object equal to a "var":

var myVar = {
    appName: 'Test',
    exec: function() {
        console.log('do stuff');  
    } 
}

Upvotes: 0

Chandu
Chandu

Reputation: 82903

Try this:

myVar.exec = function(){
    console.log('do stuff');  
} 

Upvotes: 2

Zoltan Toth
Zoltan Toth

Reputation: 47667

var myVar = { appName: 'Test' };
myVar.exec = function() {
    console.log('do stuff');  
}

Upvotes: 2

SLaks
SLaks

Reputation: 887345

myVar.exec = whatever;

Upvotes: 2

Related Questions