2017-01-12 2 views
1
// global scope 

var sayMyFavoriteColor = function(adj){ 
    return 'My ' + adj + ' color is ' + this.favoriteColor; + '!' 
}; 

var callFnTest = function (opts) { 
    return sayMyFavoriteColor.call(this, opts); 
}; 

this.favoriteColor = 'Brown'; //adding a global variable to window 
i.e. var favoriteColor = 'Brown' 

callFnTest('most disliked') 
"My most disliked color is Brown" 

제 질문은 우리가 this을 전달하고 있기 때문에 그것이 창을 가리키고 있다는 것입니다. 맞습니까?함수에 중첩 된 호출 및 적용을 가리키는 "this"키워드는 무엇입니까?

+0

@ KenY-N 제 사과! –

+0

예를 들어,'sayMyFavoriteColor' 안의'this'는'this'가'callFnTest' 안에 있는지를 나타냅니다. 'callFnTest (...) '로 불리기 때문에, this는 전역 객체를 참조하거나 엄격 모드가 활성화되면'undefined'를 참조합니다. 아직 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this'와 같은 'this'에 대한 기사를 읽는 것이 좋습니다. –

+0

@FelixKling 그래서'return sayMyFavoriteColor.call (this, opts);'문을 0으로 설정해야합니다. 즉, 하드 코딩 된'this' 참조 대신 맥락에서'favoriteColor : 'Plaid' 속성을 가진 객체가 있다면 말입니다. 그 색은 격자 무늬일까요? 권리? –

답변

0

변경되지 않습니다. 이 키워드는 클래스의 인스턴스를 사용할 때만 사용할 수 있습니다. 기본적으로 a.whateverFunction()으로 전화하면 athis입니다.