0

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

提琴手

例如,如何提醒 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();
4

2 回答 2

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/

于 2013-08-02T19:25:03.223 回答
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。

于 2013-08-02T19:16:13.427 回答