Function Rewrite

Because a function can return a function, you can replace the old function with new one.

Continuing with the previous example, you can take the value returned by the call to a() to overwrite the actual a() function.

a = a();

The above alerts A!, but the next time you call a() it alerts B!.

This will be useful when a function has some initial one-off work to do. The function overwrites itself after the first call in order to avoid doing unnecessary repetitive work every time it's called.

In the example above, we redefined the function from the outside, we got the returned value and assigned it back to the function. The function can also rewrite itself from the inside.

function a() {
    alert('A!');
    a = function() {
        alert('B!');
    };
}

If you call this function for the first time, it will Alert A!. Redefine the global variable a, and assign a new function to it.

Every subsequent time that the function is called, it will alert B!

Below is another example that combines several of the function techniques.

snippet
var a = function() {
    function someSetup() {
        var setup = 'done';
    }

    function actualWork() {
        alert('Worky-worky');
    }
    someSetup();
    return actualWork;
}();

In this example:

  • You have private functions—someSetup() and actualWork().
  • A self-invoking function—the function a() calls itself using the parentheses following its definition.
  • The function executes for the first time, calls someSetup() and then returns a reference to the variable actualWork, which is a function.
  • Because the whole thing starts with var a =..., the value returned by the self-invoked function is assigned to a.

In real time, these techniques will be useful when working in the browser environment. You can have a function determine the best way to do the work in the current browser, then redefine itself, so that the "browser feature sniffing" is done only once.

Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents