8

Is it possible to declare variables in JavaScript inside an object declaration? I'm looking for something similar to

var myObject = {
    myLabel: (var myVariable)
};

instead of having to write

var myVariable;
var myObject = {
    myLabel: myVariable
};

EDIT

I want this in the context of Node.JS. This is what I have:

var server = {};
var database = {};
var moar = {};

module.exports = {
    server: server,
    database: databse,
    moar: moar
};

doStuffAsync(function callback() {
    // Populate variables
    server = stuff();
    database = stuff2();
});
5
  • 4
    why would you need that? Commented Jan 15, 2013 at 14:13
  • 1
    myObject.myLabel would be undefined anyway, just like myObject.yourLabel, so what's the point? Commented Jan 15, 2013 at 14:15
  • Edited question to clarify why I want this. Commented Jan 15, 2013 at 14:19
  • why don't you pass module.exports to your doStuffAsync function so that you can set server and database directly at that object? Commented Jan 15, 2013 at 14:22
  • The only reason I can think of doing this is to save one line of code. If you're worried about the number of lines of code, look into minification instead of destroying your readability. Commented Jan 15, 2013 at 14:26

2 Answers 2

9

If you want to scope a variable inside an object you can use IIFE (immediately invoked function expressions)

var myObject = {
    a_variable_proxy : (function(){ 
        var myvariable = 'hello'; 
        return myvariable; 
    })()
};
Sign up to request clarification or add additional context in comments.

4 Comments

sould be a_variable_proxy : (function(){ var myvariable; return myvariable })() otherwise it is a syntax error
Need to remove the semi-colon :)
Maybe that's what the OP is looking for. But technically the variable is not scoped to the object as you said, it's scoped to the IIFE.
@bfavaretto but since it returns the variable, it can be accessed within the class. (new reply to an old comment, but hope it will help a new comer.)
3

You can assign a value to a key directly.

If you now have:

var myVariable = 'some value';
var myObject = {
    myLabel: myVariable
};

you can replace it with:

var myObject = {
    myLabel: 'some value'
};

1 Comment

That is something he/she was trying to avoid.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.