如何从变量外部访问JavaScript对象

时间:2013-08-02 19:10:17

标签: javascript object scope

我在一个变量中有JavaScript对象,我试图从它外面访问它。它的当前形式只是警告整个函数的代码。我知道这与变量范围有关。

JsFiddle

如何提醒,例如,id 1的名称?

var LocalStorage = function() {
    var queries = [
        {id: 1, name: "Mike", age: 28},
        {id: 2, name: "Jane", age: 18},
        {id: 3, name: "Miles", age: 28},
    ];
}

var app = {
    initialize: function() {
        alert(LocalStorage);
    }
};

app.initialize();

2 个答案:

答案 0 :(得分:1)

var LocalStorage = new (function() {
    var queries = [
        {id: 1, name: "Mike", age: 28},
        {id: 2, name: "Jane", age: 18},
        {id: 3, name: "Miles", age: 28},
    ];
    return queries
})()

var app = {
    initialize: function() {
        alert(LocalStorage[0].id);
    }
};

app.initialize();

http://jsfiddle.net/qKJag/3/

但这不是那么好的方式。如果您只使用Array,则不需要make函数LocalStorage。

答案 1 :(得分:1)

您希望将变量指定为对象本身的属性。

var LocalStorage = new (function() {
    this.queries = [
        {id: 1, name: "Mike", age: 28},
        {id: 2, name: "Jane", age: 18},
        {id: 3, name: "Miles", age: 28},
    ];
    this.foo = "Bar";
})()

var app = {
    initialize: function() {
        alert(LocalStorage.queries[0].name); //Alerts "Mike"
        alert(LocalStorage.foo); //Alerts "bar"
    }
};

app.initialize();

http://jsfiddle.net/qKJag/7/