2011-12-16 3 views
8

변수에 함수를 캐싱하여 코드를 작게하려고했습니다. 예를 들어 :function.call을 변수에 저장할 때 "객체가 함수가 아닙니다"

function test(){ 
    var a = Array.prototype.slice, 
    b = a.call(arguments); 
    // Do something 
    setTimeout(function(){ 
    var c = a.call(arguments); 
    // Do something else 
    }, 200); 
} 

그래서 대신 Array.prototype.slice.call(arguments)를 호출, 난 그냥 a.call(arguments); 할 수 있습니다.

캐시를 Array.prototype.slice.call으로 작게 만들려고했으나 작동하지 않았습니다.

function test(){ 
    var a = Array.prototype.slice.call, 
    b = a(arguments); 
    // Do something 
    setTimeout(function(){ 
    var c = a(arguments); 
    // Do something else 
    }, 200); 
} 

TypeError: object is not a function 나에게 제공합니다. 왜 그런가요?

typeof Array.prototype.slice.call은 예상대로 "function"을 반환합니다.

변수에 .call을 저장할 수없는 이유는 무엇입니까?

+0

javascript 엔진에서이 오류를 줬습니까? –

+0

가능한 복제본 [Array.prototype.slice.call()을 어떻게 참조할까요?] (http://stackoverflow.com/questions/6835315/how-do-you-reference-array-prototype-slice-call) – pimvdb

+0

@DanD .: Chrome 16. –

답변

7

Function.prototype.callthis로 전달 함수에서 동작하는 통상의 함수인지 에러가 발생 지금 consolewindow하지 지칭 this 호출을 포함한다.

call을 변수에서 호출하면 thiswindow이되며 이는 기능이 아닙니다.
당신은 call.call(slice, someArray, arg1, arg2)

+0

멋지다. 'var a = Array.prototype.slice, b = a.call; b.call (a, arguments)'를 호출합니다. 그래서,'.call'을 복사 할 때'this '를 "바인딩"할 수있는 방법이 있습니까? –

+2

@Rocket : https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind – SLaks

+0

그래서'var a = Array.prototype.slice.call.bind (Array.prototype.slice)'?편집 : 와우, 그 실제로 작동합니다! 편집 2 : 페이지'var 슬라이스 = Function.prototype.call.bind (Array.prototype.slice);에 따르면'작품도! 산뜻한! –

5

이 시도 :

function test(){ 
    var a = function(args){ 
     return Array.prototype.slice.call(args); 
    }; 
    b = a(arguments); 
    // Do something 
    setTimeout(function(){ 
    var c = a(arguments); 
    // Do something else 
    }, 200); 
} 

이 같은 오류는 같은 일을 시도하는 경우 발생합니다 :

var log = console.log; 
log("Hello"); 

이유는이 작업을 수행 할 때의 기능 x을 (할당하는 것입니다 내 예 : log)를 변수 log으로 변경하십시오. BUT 함수는 this is not an object

+0

이상한,'var log = console.log; log ('a');는 Chrome 16에서'TypeError : Illegal invocation'을 주지만,'var logX = console.log.bind (console); logX ('a');'작동 : -P –

4

문제는 call은 소유자 (그 this가) 함수가 될 것으로 예상하는 방법 (객체에 속한 함수)라는 것이다 작성해야합니다. a = Array.prototype.slice.call으로 작성하면 함수를 복사하지만 소유자는 복사하지 않습니다.

"개체가 함수가 아닙니다"라는 메시지는 a이 기능이 아니라는 것을 나타내는 것이 아니며, this은 기능이 아닙니다. 기술적으로는 a.call(Array.prototype.slice, arguments)을 작성하여 설명하는 것을 달성 할 수 있지만 분명히 원하는 것은 아닙니다!

+0

쿨,'a.call (Array.prototype.slice, arguments)'실제로 작동합니다. 나는 당신이 함수를 복사 할 때'this'가 올바르게 참조 될 것이라고 생각했습니다. –

+2

@Rocket : 아니요 - 'a.foo = b.foo' 또는 A.prototype.foo = B.prototype.foo'와 같은 것을 할 수 있어야하기 때문에 불가능합니다. 한 객체에서 다른 객체로 메소드를 복사합니다. 'a.foo() '에 대한 호출이'a'보다는'b'에서 작동한다면 그것은 몹시 혼란 스러울 것입니다! – ruakh

관련 문제