2010-07-22 6 views
2

내 문서의 모든 JavaScript 함수를 반복 할 수 있고 예를 들어 alert('ok');을 추가 할 수 있습니다.즉석에서 javacript 함수 반복 및 변경

내가 가진 그렇다면 :

function a(num) { 
    return num; 
} 

내 자바 스크립트 코드를 실행하고이 함수를 호출 한 후, 실제로 수행합니다

{ 
    alert('ok'); 
    return num; 
} 

은 내가 창을 사용하여 기능에 액세스 할 수 있습니다 알고 [. funcName],하지만 어떻게 모든 함수를 반복하고 그들을 편집 할 수 있습니까?

감사

PS :이 아주 좋은 생각이 아니다 알고 있지만 그냥 디버그 환경

답변

1
for (var i in window) { 
    if (typeof window[i] == 'function') console.log(i); // logs the function name 
} 

이 당신에게 기능의 목록을 가져옵니다위한거야. 자바 스크립트에서 함수를 수정할 수는 없으며 단지 래핑 할 수만 있습니다. 즉, 함수의 복사본을 만들고 원본을 래퍼로 바꾸는 것을 의미합니다.

function a(num) { return num;} 

다음 우리는이처럼 포장 : 이것은 당신에게 세계 유일의 공간 기능, 예를 제공

functionName = 'a'; // original function name 
window['_original_' + functionName] = window[functionName]; // putting it in a safe place 
window[functionName] = function() { // creating wrapper 
    alert('ok'); //logger function 
    return window['_original_' + functionName].apply(null, arguments); //invoke original 
} 

말, 우리는이 기능이 jQuery 플러그인을 로깅하지 않습니다. 모든 기능을 로그하려면 Firebug의 프로파일 러를 사용하십시오.

+0

감사합니다! 하지만 단지 점, 그것은 적합한 방식으로 작동하지 않을입니다 \t \t 창 [I]는 = 함수 (X) { \t \t \t 창 함수() { \t \t \t \t 경보 (X); \t \t \t \t return window [ '_ original_'+ x] .apply (null, arguments); \t \t \t} \t \t} (i); – Fernando

0

기존 함수의 코드를 수정하는 대신 기존 함수를 래핑하는 인터셉터 함수를 사용해 보았습니다. 간단한 구현 (더 개선 할 수 있습니다)

function intercept(object, methodBindName, interceptor) { 
    var oldMethod = object[methodBindName]; 
    object[methodBindName] = function() { 
     interceptor.apply(null, arguments); 
     return oldMethod.apply(object, arguments); 
    } 
} 

function test1(msg) {alert(msg);} 
function test2() {alert('hi');} 

var methodNames = ['test1', 'test2']; 

for(var i = 0; i < methodNames.length; i++) { 
    intercept(window, methodNames[i], function(){alert('Hello');}) 
} 
test1('foo'); 
test2(); 
+0

oldMethod.apply (object, arguments); 또한 –

+0

@ Alisey 값을 반환해야합니다. 업데이트 됨. 지적 해 주셔서 고마워요. –

+0

두 함수 모두'.apply (this, arguments)'가 아닌가? 때때로 그 함수들은'객체'의 문맥에서 호출되지 않을 수도 있습니다. – gnarf