Javascript - 修改函数或从字符串中评估函数

时间:2013-12-10 06:00:48

标签: javascript function eval

这就是我目前所拥有的:

test(function(){
    console.dir('testing');
});

// Input a function

function test(fn){
    console.dir(fn.toString().replace('dir','log'));
    // console: function (){console.log('testing');}

    // try to evaluate string back to a function
    eval(fn.toString().replace('dir','log'));
}

我可以修改一个函数中的某些东西(例如,'测试'到'hello world')

或将修改后的函数字符串评估回函数?

感谢

2 个答案:

答案 0 :(得分:1)

试试这个:

test(function(){
    console.dir('testing');
    alert('done');
});

// Input a function

function test(fn){
    console.dir(fn.toString().replace('dir','log'));
    // console: function (){console.log('testing');}

    // try to evaluate string back to a function
    var f;
    eval('f = ' + fn.toString().replace('dir','log'));
    f();

}

答案 1 :(得分:0)

以下代码产生相同的结果:

function test(action, fn) {
    fn(action);
}
test('log', function (action) {
    console[action]('testing');
});