最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript: Declare variable inside object declaration - Stack Overflow

programmeradmin0浏览0评论

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
  • 4 why would you need that? – t.niese Commented Jan 15, 2013 at 14:13
  • 1 myObject.myLabel would be undefined anyway, just like myObject.yourLabel, so what's the point? – danronmoon Commented Jan 15, 2013 at 14:15
  • Edited question to clarify why I want this. – Randomblue 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? – t.niese 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. – jbabey Commented Jan 15, 2013 at 14:26
Add a comment  | 

2 Answers 2

Reset to default 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; 
    })()
};

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'
};
发布评论

评论列表(0)

  1. 暂无评论