Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Declare variable inside object declaration

Tags:

javascript

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();
});
like image 789
Randomblue Avatar asked Jan 15 '23 12:01

Randomblue


1 Answers

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; 
    })()
};
like image 169
palerdot Avatar answered Jan 22 '23 10:01

palerdot