0

I am aware you can access properties of objects in javascript using variables like this Object['property'] but I want to access the Object using a variable too.

// The object and his function
var Foo = {};
    Foo.bar = function() { console.log("I am a useful function dood"); }

// The accessors
var obj = 'Foo';
var method = 'bar';

But when I try it in the way I think is right, I get the following. As all links in the world seem to be about accessing object properties with variables I don't seem to be able to sift one out that accesses objects like this too.

typeof obj           // "object"
typeof Foo[method]   // "function"
typeof [obj].foo     // undefined
typeof [obj][method] // undefined <-- This is what I'm trying to use

Am I able to access the object like this?

EDIT

According to answers, if the object is globally scoped I could use window[obj][method] but the above is contained in an immediately invoked function like this:

(function(){
    // The stuff from above...
})();

Will this work I will have to put this into an identifiable var that is globally scoped?

PS I will never ever use eval();

Ben Harvey
  • 1,793
  • 2
  • 16
  • 23

1 Answers1

1

If your Foo object is at the global object then :

window[obj][method]() //I am a useful function dood`

Else , you will need to supply more info.

Royi Namir
  • 144,742
  • 138
  • 468
  • 792
  • Ah yes, that makes sense but the object is not in the global scope, it is in an immediately invoked function, like this: ````(function () { // All the stuff from above })();```` Is there any way of accessing it this way or do I need to make a reference to a globally scoped container for the functionality? – Ben Harvey Oct 07 '15 at 13:13