Flerex
Flerex

Reputation: 354

How to edit a function without rewrite its content?

I have two scripts but I cannot access to one of them. How I would edit the content of a function without rewriting it?

Example:

I know this can edit the function:

<script>
function a() {
alert('hi');
}
</script>
<script>
function a() {
alert('hi');
console.log('hi');
}
</script>

But I don't want to rewrite again the "alert('hi')".

Upvotes: 2

Views: 195

Answers (4)

T.J. Crowder
T.J. Crowder

Reputation: 1074268

You can steal the function's symbol, like this:

var b = a;             // <== Takes the original `a` and remembers it as `b`
a = function() {       // <== Assigns a new function to `a`
    var rv = b();      // <== Calls what used to be `a`, remembers its return value
    console.log("hi");
    return rv;         // <== Returns what the old function returned
};

Of course, if you don't need the return value thing, you can leave it out, but if you're pretending to be the old function, probably best to return what it returns.

If you need to pass along arguments to it and just want to pass all of the arguments your new function receives, you can do that with Function#apply and the special arguments pseudo-array:

var b = a;
a = function() {
    var rv = b.apply(this, arguments); // Calls the original `a` with the current 
                                       // `this` and all the args we were given
    console.log("hi");
    return rv;
};

Upvotes: 3

Ilya Kharlamov
Ilya Kharlamov

Reputation: 3932

Another option is to redefine the function source by search & replace:

eval(a.toString().replace(/(alert\(\'hi\'\)\;)/,"$1\nconsole.log('hi');"));

Upvotes: 0

haim770
haim770

Reputation: 49095

You can serialize the original function into a string, construct a new one and append the new line to it:

function a() {
     alert('a');
}

var b = new Function('(' + a + ")(); alert('b');")

b(); // would alert twice, 'a' & 'b'

Upvotes: 0

elixenide
elixenide

Reputation: 44833

Try this: set a new function to the old one, then reassign the old one:

function a() {
    alert('hi');
}
b = a;
a = function()
{
    b();
    console.log('hi');
}
a();

Note that you have to assign the new a using an expression: a = function()... If you just do function a()..., you get recursion and exceed the maximum call stack size.

Upvotes: 0

Related Questions