Frage

Ich schreibe hier einige Bookmarklets und ich habe einige Fragen zu eingebauten JavaScript-Funktionen.

Nehmen wir an, ich möchte die integrierte Aufforderungsfunktion ersetzen (nicht unbedingt in einem Bookmarklet).Das scheint leicht genug zu sein, ist aber eine Möglichkeit, die integrierte Aufforderungsfunktion innerhalb dieses Ersatzes aufzurufen? generasacodicetagpre.

Ich konnte das Scoping nicht bekommen, um richtig auszuarbeiten;Dieses Beispiel ergibt unendliche Rekursion.

Gibt es auch eine Möglichkeit, das Standardverhalten einer integrierten JavaScript-Funktion wiederherzustellen (ohne auf eine zusätzliche Referenz aufzuhängen).

War es hilfreich?

Lösung

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

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top