2014-05-09 1 views
2

아래 코드를보고 설명하십시오. 내가 뭘 잘못하고있는 걸까요?JavaScript에서 call() 메서드의 요점을 이해할 수 없습니다.

 

    function doStuff(a, b){ 
     return a + b + 1 ; 
    } 

    var myContext = { 
     c: 1, 
     d: 3 
    }; 

// myContext = this (result => 5) 
    doStuff.call(myContext,myContext.c,myContext.d) 

// ... so why doesn't the below work? (result => NaN) 
    doStuff.call(myContext,this.c,this.d) 

// To make the above work, i must replace "this" with "myContext" (result => 5)... 
    doStuff.call(myContext,myContext.c,myContext.d) 

// ...which is no different to... 
    doStuff(myContext.c,myContext.d) 

// ...so what was the point of call() method? 

나는 두껍습니까?

+1

'같이 Function.prototype 실제로이지고있다 .call()'은 함수 안에 this를 설정하므로, doStuff.call (myContext); 할 수있는 함수 doStuff() {return this.a + this.b +1}'이 있으면 – raser

+0

함수의 * this * 매개 변수입니다. 그것의 [실행 컨텍스트 *] (http://ecma-international.org/ecma-262/5.1/#sec-10.3)의 일부이기 때문에 그것은 "컨텍스트"자체가 아닙니다. – RobG

답변

3

call의 요점은 this의 값을 범위 내로 설정하는 것입니다. doStuffthis내에서 내에서 기능을 사용하지 않으므로 call을 사용하면 무의미합니다.

function doStuff(a, b) { 
    return this.sum(a, b); 
} 
var obj = { 
    sum: function(a, b) { 
     return a + b; 
    } 
}; 
console.log(doStuff.call(obj, 3, 4)); // 7, because `obj` has a `sum` property 
console.log(doStuff(3, 4));   // Fails with an error that `this.sum` is not a function 

을 왜하지 아래 작업을 수행합니다

은 여기 중요한 예입니다?

this.c 있으므로 현재 this 값이 무엇이든지 사용 doStuff에 호출 전에 을 평가

doStuff.call(myContext,this.c,this.d)

(결과 => NaN이). 이 코드를 어떻게 호출하고 있는지, thisc 또는 d 속성이없는 전역 객체 (브라우저의 윈도우 객체)입니다 (느슨한 모드). (thisundefined 때문에 엄격 모드, 다시 당신이 전화하고 방법에 대한 가정을 만들고, 당신은 예외를 얻을 것이라고 당신은 undefined에서 속성을 검색 할 수 없습니다.)

+1

이제 이해가됩니다. 건배. – neahan

0

.call.apply는 기능입니다 어떤 방법으로 'this'이 의미하는 '조작'방법.

doStuff.call(myContext, myContext.c, myContext.d) : 여기 당신이 doStuff 기능 컨텍스트로 myContext을 설정 한 당신이 this, 를 사용하여 내부 그것을 참조 할 수 있으며 당신이 그것에 두 개의 인수를 전달했습니다, myContext.d을 myContext.c 그것은 당신이 의도 한대로 ...


doStuff.call(myContext, this.c, this.d) 작동합니다 다시 myContext입니다 doStuff() 에 대한 상황에 있지만 패스를했습니다.c.d의 속성이 this 인 경우 을 가리키며 (글로벌 개체, 창) 귀하의 경우 나타납니다. 그래서 doStuff의 컨텍스트 myContext이며, 매개 변수 및 함수에 global.c.d 속성을 전달하는이 함수를 호출하는 상황에서 this === window, 때문에 2 개 undefined의, 입니다.

function doStuff() { 

    return this.a + this.b + 1; 

    // here it looks whatever this is set to 
    // by `.call()` or `.apply()` methods 

} 

과 같이 호출 :이 같은 'doStuff'를 재정의하는 경우


return undefined + undefined + 1; 비수 (NaN) :

var sum = doStuff.call(myContext); 

// notice that using `.call` here 
// means that 'myContext' is manualy set 
// as `this` value inside the function above 
// and is refered to by dynamic variable 'this' 
관련 문제