JavaScript:在对象声明中声明变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14339555/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 21:22:30  来源:igfitidea点击:

JavaScript: Declare variable inside object declaration

javascript

提问by Randomblue

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

是否可以在 JavaScript 中的对象声明中声明变量?我正在寻找类似的东西

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:

我希望在 Node.JS 的上下文中使用它。这就是我所拥有的:

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

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

doStuffAsync(function callback() {
    // Populate variables
    server = stuff();
    database = stuff2();
});

回答by palerdot

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

如果你想在一个对象中定义一个变量,你可以使用 IIFE(立即调用的函数表达式)

var myObject = {
    a_variable_proxy : (function(){ 
        var myvariable = 'hello'; 
        return myvariable; 
    })()
};

回答by Jan Han?i?

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'
};