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();
});
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();
});
Share
Improve this question
edited Jan 15, 2013 at 14:19
Randomblue
asked Jan 15, 2013 at 14:11
RandomblueRandomblue
116k150 gold badges362 silver badges557 bronze badges
5
|
2 Answers
Reset to default 9If 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;
})()
};
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'
};
module.exports
to your doStuffAsync function so that you can setserver
anddatabase
directly at that object? – t.niese Commented Jan 15, 2013 at 14:22