2012-12-18 5 views
0

자바에서는 특정 코드 섹션에서 함수가 호출되지 않도록 할 수있는 방법이 있습니까? "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을 구현해야합니까?

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입니다 :

답변

3

당신은의 종류과 같이이 작업을 수행 할 수 있습니다.

+2

전역이 아닌 범위에 있다면 로컬 변수 –

+0

Nope를 사용하여 경고 마스킹으로 벗어날 수 있습니다. 실제로 누군가가 실제로'window.alert'를 지정하는 것은 드문 일입니다. –

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 
+1

또는 이벤트 더 나은 ...'경고 = 콘솔 : 데모 작업

// 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"); })(); 

.log' –

관련 문제