我在一个变量中有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();
答案 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();
但这不是那么好的方式。如果您只使用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();