Modify a function or evaluate a function from string

This is what I currently have:

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

Can I modify something in a function (eg,'testing' to 'hello world')

or evaluate modified string of function back to a function?

thanks


try this:

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');
});
链接地址: http://www.djcxy.com/p/2878.html

上一篇: 这与功能的强制性绑定

下一篇: 修改函数或从字符串评估函数