1

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

2 Answers 2

1

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

}

Sign up to request clarification or add additional context in comments.

3 Comments

Oh man, this is so simple and can't imagine that I didn't have thought of that. Thanks!
More expclicit would be var f = new Function(...code...);. I don't think it's a good idea to use a regular expression to parse script, or any programming code.
-1 This would break code which contained part of a property name with dir in it, e.g. obj.direction would be changed to obj.logection. Also, this does not work if there is more than one call to console.dir, as String.prototype.replace only replaces the first instance found if passed a string as the first argument.
0

Following code produces the same result :

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.