将javascript字符串转换为对象方法并调用它?

时间:2012-04-05 03:03:42

标签: javascript

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

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

2 个答案:

答案 0 :(得分:2)

我认为你在寻找:

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

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

调用身体的onclick功能。

答案 1 :(得分:0)

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

fn.call(your object);