Javascript-修改函数或从字符串中计算函数

Javascript - Modify a function or evaluate a function from string

本文关键字:函数 计算 字符串 修改 Javascript-      更新时间:2024-06-04

这就是我目前拥有的:

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'));
}

我可以修改函数中的某些内容吗(例如,"测试"为"你好世界")

或者将修改后的函数字符串求值回函数?

感谢

试试这个:

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();

}

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

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