Question

I am writing some bookmarklets here and I have some questions related to built-in javascript functions.

Let's say I want to replace the built-in prompt function (not necessarily in a bookmarklet). That seems easy enough, but is there a way to call the builtin prompt function from within this replacement?

prompt = function(message){
    var tmp = prompt(message);
    hook(tmp);
    return tmp;
}

I couldn't get the scoping to work out right; this example yields infinite recursion.

Also is there a way to restore the default behavior of a builtin javascript function that has been replaced (without hanging on to an extra reference).

Was it helpful?

Solution

(function () {
    var old_prompt = prompt;
    prompt = function (msg) {
        var tmp = old_prompt(msg);
        hook(tmp);
        return tmp;
    };
    prompt.restore = function () { prompt = old_prompt; }
    // analogous for other functions you want to replace
})();

Wrapping it up in a (self-executing) function ensures that old_prompt doesn't leak to the outside. You do need to expose something though. I chose to provide a function doing the restoring, for convenience and perhaps, one could say, future-proofing and encapsulation. As long as higher order functions refrain from fiddling with someone else's scope...

Also, no, it's (I'd assume) not possible to restore the previous value of a variable without any reference to it (the old value), even if that value happened to be a built-in. Even if it was possible, it'd be a pretty obscure trick - this way works, so let's just stick with it.

(Credit for func.restore goes to Martijn)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top