Fisu
Fisu

Reputation: 3324

How to access a JavaScript object from outside of the variable

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.

JsFiddle

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

Answers (2)

Retsam
Retsam

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();

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

Upvotes: 1

Mihail
Mihail

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();

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

But it is no so good way. If you will use only Array, than you not need make function LocalStorage.

Upvotes: 1

Related Questions