Reputation: 116443
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();
});
Upvotes: 8
Views: 24501
Reputation: 7652
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;
})()
};
Upvotes: 9
Reputation: 53929
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'
};
Upvotes: 3