1

I've come across some code which allows you to convert a string of a function name to a function and use it:

var strFun = "someFunction";
var strParam = "this is the parameter";

//Create the function
var fn = window[strFun];

//Call the function
fn(strParam);

I was wondering if there was a way to do the same for object methods, e.g.:

var fn = window["onclick"];
var body = document.body;
body.onclick = function() {
    alert('yo');
}
// This won't work [Uncaught TypeError: Object #<HTMLBodyElement> has no method 'fn']
body.fn(); // expecting body.onclick(); via substitution of fn with a onclick function
3
  • @Derek: your code still doesn't make sense. You're creating one thing, and calling another. Commented Apr 5, 2012 at 3:14
  • Once again, if you want to attach click handlers, you don't need all that. Use addEventListener. Commented Apr 5, 2012 at 3:15
  • I'm going after the abstract meaning of the code so body.fn() == body.onclick() Commented Apr 5, 2012 at 3:19

2 Answers 2

2

I think you're looking for:

var body = document.body;
body.onclick = function() {
    alert('yo');
}

var strfun = 'onclick';
var fn = body[strfun];
fn();

To call the onclick function of the body.

Sign up to request clarification or add additional context in comments.

Comments

0

You can just call the function in the context of your object:

fn.call(your object);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.