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

时间:2012-12-18 07:05:07

标签: javascript

在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 个答案:

答案 0 :(得分: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;

但这是主要的hax。

答案 1 :(得分: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

答案 2 :(得分:0)

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

答案 3 :(得分: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/