Javascript:有没有办法在不使用eval()的情况下将字符串用作回调?

gee*_*man 3 javascript string eval callback

所以我需要在我的一个函数中进行回调,但是由于整个程序的工作方式,我需要以字符串的形式而不是函数本身传递回调函数名.

例如:

function doThings(callback){
    alert('hello');
    eval(callback + '();');
}

function test(){
    alert('world!');
}

var func = 'test';

doThings(func);
Run Code Online (Sandbox Code Playgroud)

简而言之,我正在尝试动态更改使用的函数,我必须使用字符串来表示回调函数,而不是实际的函数引用.

我一直在阅读eval是邪恶的 - 有没有办法做到这一点没有eval()?

编辑:我没有能力事先列出对象中的函数.我还需要将一个数组作为单独的参数传递给这个函数,并且由于某些原因.apply()不能很好地兼容window[callback]()

Que*_*tin 6

将函数存储在对象中.使用属性名称来访问它们.

function doThings(callback) {
  alert('hello');
  my_possible_functions[callback]();
}

function test() {
  alert('world!');
}

var my_possible_functions = {};
my_possible_functions.test = test;


var func = 'test';
doThings(func);
Run Code Online (Sandbox Code Playgroud)


Ste*_*tis 5

你可以这样做,以这种方式。

function doThings(callback){
    alert('hello');
    window[callback]();
}

function test(){
    alert('world!');
}

var func = 'test';

doThings(func);
Run Code Online (Sandbox Code Playgroud)

或者您可以在字符串中传递完整函数并使用Function构造函数。

function doThings(callback){
    alert('hello');
    (new Function('return '+callback)())();
}

function test(){
    alert('world!');
}

var func = test.toString();

doThings(func);
Run Code Online (Sandbox Code Playgroud)