1

Javascriptでは、コードの特定のセクションで関数が呼び出されないようにする方法はありますか?コードの特定のセクションで関数「alert」が呼び出されないようにしたい。

alert("Hi!"); //this should work normally
var al = alert
//the function "alert" cannot be called after this point

preventFunctionFromBeingCalled(alert, "Do not use alert here: use the abbreviation 'al' instead.");

alert("Hi!"); //this should throw an error, because "console.log" should be used instead here
allowFunctionToBeCalled(alert);
//the function "alert" can be called after this point
alert("Hi!"); //this should work normally

この場合、どのように関数を実装する必要がallowFunctionToBeCalledありpreventFunctionFromBeingCalledますか?

4

4 に答える 4

3

あなたは次のようにこれを達成することができます:

window._alert = window.alert;
window.alert = function() {throw new Error("Do not use alert here, use console.log instead");};

// later:
window.alert = window._alert;
delete window._alert;

しかし、それは大きな問題です。

于 2012-12-18T07:08:20.023 に答える
1
var a = alert; //save the alert function
alert = function(){}; //change to a function you want (you can throw an error in it)
alert("something"); //this will call the empty function bellow
alert = a; //change alert back to it's original function
于 2012-12-18T07:08:01.017 に答える
0

「alert()」よりも「window.alert()」がなぜですか?ここ。http://bytes.com/topic/javascript/answers/832371-why-window-alert-over-alerthere

于 2012-12-18T07:11:11.683 に答える
0

一時的window.alertに何もしない関数に再割り当てして、ローカル変数で元の値を非表示にすることができます。

// replace alert
var _alert = window.alert;
window.alert = function() {};

// code here can't call alert
// code in this closure can't even access the saved version of window.alert
(function() {
    alert("hello1");
})();

// restore alert
window.alert = _alert;

// code here can call alert
(function() {
    alert("hello2");
})();

作業デモ: http: //jsfiddle.net/jfriend00/mGC3x/

于 2012-12-18T07:16:58.023 に答える