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

在这种情况下,我应该如何实现功能allowFunctionToBeCalledpreventFunctionFromBeingCalled

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

您可以临时重新分配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 回答
0

你可以找到为什么是“window.alert()”而不是“alert()”?这里。http://bytes.com/topic/javascript/answers/832371-why-window-alert-over-alerthere

于 2012-12-18T07:11:11.683 回答