Is it possible to call a method from an object using a string?
var elem = $('#test'); //<div id="test"></div>
var str = "attr('id')";
//This is what I'm trying to achieve
elem.attr('id'); //test
//What I've tried so far
elem.str; //undefined
elem.str(); //Object [object Object] has no method 'str'
var fn = eval(str); //attr is not defined
eval(elem.toString()+'.'+str); //Unexpected identifier
//Only solution I've found so far,
//but is not an option for me
//because this code is in a function
//so the element and method call
//get passed in and I wouldn't know
//what they are
eval($('#test').attr('id')); //test
UPDATE
This is my final, working answer:
After running this code in the console
The post-form element now has a new ID, no problems at all. This works for methods that take multiple arguments, a single argument or no arguments at all. Recap:
That’s the safest, most reliable approach I can think of, really
What ever you do DON’T USE EVAL:
It’s the same basic principle as you’d use with any objects (remember that functions are objects all on their own in JS – and jQuery objects are, well, objects, too). This means that methods can be accessed in the exact same way as properties can:
So just break the string apart, and use the method name like you would an object property and you’re all set to go.
Just remember: When all you have is the eval hammer, everything looks like your thumb.
Brendan Eich
If there is a chance of multiple arguments being passed to whatever method, you can sort of work your way around that, too (I think – well: logic dictates, but it’s rather late and logic is getting beat up by Gin pretty bad now):
This applies the method of whatever element/object you’re dealing with to itself, thus not changing the caller context (
thiswill still point to the object within the method) and it passes an array of arguments that will be passed to the called method.