Industrial
Industrial

Reputation: 42778

Accessing property from inside method using JavaScript

I'm trying to access a property from inside an object. When I access the property by manually entering its path, I can retrieve it, but not when doing it dynamically.

What have I missed below?

var myApp = {
    cache : {},
    init: function() {
        myApp.cache.akey = 'A value'; // Set the cached value
        myApp.get('cache', 'akey'); 
    },
    get: function(from, key ) {
        console.log(myApp.from.key); // undefined
        console.log(myApp.cache.akey); // A value
    }
};

Upvotes: 0

Views: 329

Answers (2)

Esailija
Esailija

Reputation: 140230

The dot access is literal, if you wanna access by string contained in a variable use subscript notation:

get: function(from, key ) {
    console.log(myApp[from][key]); // Assume from === "cache" and key === "akey", this accesses myApp.cache.akey

}

Upvotes: 0

Doug Domeny
Doug Domeny

Reputation: 4470

The arguments 'from' and 'key' are not referenced in your example, instead the properties are literals.

Try

myApp[from][key]

Upvotes: 1

Related Questions