我遇到了一些代码,它允许您将函数名称的字符串转换为函数并使用它:
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