1

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?

1
  • 2
    You realise javascript objects are essentially just maps that you can add any key/value pair you want to? Commented Mar 5, 2012 at 18:57

5 Answers 5

2
myVar.exec = whatever;

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

2

Try this:

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

Comments

0

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.

3 Comments

Yes! That's great! Thank you!
I'm happy my solution helped! Would you consider marking it as the answer?
I didn't realize until you mentioned it. I just did. Thank you!
0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.