开发者问题收集

防止在特定代码段中调用某个函数

2012-12-18
161

在 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

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;

但这是一个重大黑客攻击。

Niet the Dark Absol
2012-12-18
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
shift66
2012-12-18

您可以在这里找到为什么“window.alert()”优于“alert()”? http://bytes.com/topic/javascript/answers/832371-why-window-alert-over-alerthere

Pratibha
2012-12-18