inN0Cent
inN0Cent

Reputation: 363

how to invoke a dynamically named object and its method in javascript?

I have a situation in which the name of my object will be dynamic..

i.e.

txtGrantAccess_5.GetValue();

i want to know how can I call this dynamically?

e.g.

var abcd = 'txtGrantAccess_5';
abcd.GetValue();

Please note that txtGrantAccess_5 already exists, please can you also avoid the usage of eval in your answer? I have tried understanding other questions almost similar to this but they are not the same thing...

Upvotes: 0

Views: 66

Answers (3)

Alex Wayne
Alex Wayne

Reputation: 187024

You cannot get local variables dynamically. However, if it's a property of an object you can get it with the [] syntax.

var obj = {};
obj.foo = function() {};
obj.foo();
obj['foo'](); // same as above.

But in this case a local variable cannot be fetched dynamically at all.

var fn = function() {
  var foo = '123';
  // no way to get foo dynamically.
}

One exception is global variables. In the global scope, local variables are created as properties of the window object:

// global scope, outside of any function.
var foo = function() {};
window.foo();
window['foo'](); // same as above

Just keep in mind that lots of global variables are usually frowned upon, espcially if there is enough that you need to find dynamically like this. You probably just want a container object to keep these values in, like the first example I posted.

Upvotes: 2

promanski
promanski

Reputation: 567

Try this snippet

var abcd = 'txtGrantAccess_5';
this[abcd].GetValue();

but be careful with value of "this". If it's in a browser maybe this will help

var abcd = 'txtGrantAccess_5';
window[abcd].GetValue();

Upvotes: 0

Kong
Kong

Reputation: 9546

How about:

var container = {};
var name = 'dynamicName';
container[name] = new MyObject();
container[name].getValue()

Upvotes: 0

Related Questions