2013-02-25 1 views
0

자바 스크립트를 학습하는 동안 함수의 적용 속성을 다시 선언하려고했습니다. 지금까지 아무런 문제가 없습니다.적용 (자바 스크립트) 다시 적용 선언 내에서 Function.prototype.apply 호출

function foo() { return 1; } 
alert(foo()); // 1 
alert(foo.apply(null)); // 1 
foo.apply = function() { return 2; } 
alert(foo()); // 1 
alert(foo.apply(null)); // 2 

지금, 나는 더 무언가를 적용하고 "오래된"이 (로깅 등)에 적용 전화를 시도했다.

var old = foo.apply; 
foo.apply = function() { 
    alert("A"); 
    return old(null); 
} 
alert(foo.apply(null)); 

난 내가 얻을

foo.apply = function() { 
    alert("A"); 
    return arguments.callee[Function.prototype.apply](null); 
} 
alert(foo.apply(null)); 

시도

TypeError: Function.prototype.apply was called on [object Window], which is a object and not a function


얻을

TypeError: Property 'function apply() { [native code] }' of object function() { alert("A"); return arguments.calleeFunction.prototype.apply; } is not a function


내가 시도한 것을 실제로 수행 할 수있는 방법이 있습니까? 또는 Function.prototype.apply 네이티브 코드로 인해 일부 제한 사항이 있습니까?

+0

크롬에서 저에게 잘 작동합니다 ... – loxxy

+0

@Ioxxy 어떤 버전입니까? 붙여 넣은 출력은 Chrome의 콘솔에서 가져옵니다./ –

+0

첫 번째 솔루션은 Chrome (v25)에서 작동합니다. 어떤 브라우저를 사용하고 있습니까? –

답변

3

예. apply은 함수에 적용될 것입니다 (예, 정확하게 그 자체로). 사용자가 사용한 방법 (old())은 this value을 전역 개체 (window)로 만듭니다. (우리가 아닌 방법으로 old를 사용했습니다하지만,하지만 순수 함수로)

var old = foo.apply; // === Function.prototype.apply 
foo.apply = function() { 
    // "this" is the function foo 
    alert("A"); 
    return old.apply(this, arguments); // applying the (old) apply function on foo 
    // or better without any arguments: 
    return old.call(this); // like this(); which is foo() 
} 
alert(foo.apply(null)); 

// and the call solution with an argument: 
foo.apply = function(context) { 
    return old.call(this, context); 
    // like this.call(context); 
    // which is foo.call(context) 
    // which is like context.foo() 
} 

또한 callapply "방법"에 대한 문서를 체크 아웃 : 그래서 당신은이 작업을 수행 할 수 있습니다.

+0

Thx, 정말 유익했습니다 :) –

관련 문제