Reputation: 3324
I have JavaScript object in a variable which I'm trying to access from outside of it. It's current form just alerts the entire function's code. I know this is an issue to do with variable scope.
How do I alert, for example, the name for 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();
Upvotes: 0
Views: 2377
Reputation: 33449
You want to assign the variables as properties of the object itself.
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();
Upvotes: 1
Reputation: 1479
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();
But it is no so good way. If you will use only Array, than you not need make function LocalStorage.
Upvotes: 1