Can you alter a Javascript function after declaring it?

前端 未结 12 794
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-28 22:10

Let\'s say I have var a = function() { return 1; }. Is it possible to alter a so that a() returns 2? Perhaps by editing a

12条回答
  •  借酒劲吻你
    2020-11-28 22:32

    I used something like this to modify an existing function whose declaration was not accessible to me:

    // declare function foo
    var foo = function (a) { alert(a); };
    
    // modify function foo
    foo = new Function (
      "a",
      foo.toSource()
        .replace("alert(a)", "alert('function modified - ' + a)")
        .replace(/^function[^{]+{/i,"")  // remove everything up to and including the first curly bracket
        .replace(/}[^}]*$/i, "")  // remove last curly bracket and everything after
    );

    Instead of toSource() you could probably use toString() to get a string containing the function's declaration. Some calls to replace() to prepare the string for use with the Function Constructor and to modify the function's source.

提交回复
热议问题