1

我遇到了一些代码,它允许您将函数名称的字符串转换为函数并使用它:

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

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

//Call the function
fn(strParam);

我想知道是否有办法对对象方法做同样的事情,例如:

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
4

2 回答 2

2

我想你正在寻找:

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

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

调用body的onclick函数。

于 2012-04-05T03:15:05.887 回答
0

您可以在对象的上下文中调用该函数:

fn.call(your object);
于 2012-04-05T03:08:34.023 回答