on
Javascript this, 자바스크립트 this
Javascript this, 자바스크립트 this
mdn사이트에서 this의 요약을보면 javascript에서 함수의 this는 타언어들과 조금 다르게 작동한다고 적혀있다.
javascript에서 this의 값은 함수를 호출하는 방법에 의해 결정되는데 이러한 이유로 함수가 호출될 때 마다 this가 다를 수 있다.
예를들면
1 2 3 4 5 6 7 8 9 const print_this = { print : function () { console .log( this ); }, } print_this.print(); //print_this 오브젝트 const printFunction = print_this.print; printFunction(); //Window 오브젝트 cs
위 코드에서 print_this의 print 함수를 실행하면 console.log의 this가 print_this 오브젝트를 출력하고,
print_this.print함수를 담은 함수 printFunction()을 실행하면 console.log의 this는 Window 오브젝트를 출력한다.
javascript에서 this는 누가 호출하는 방법에 따라 달라지는데
print_this.print()는 print_this가 print()함수를 직접 부르는것이기 때문에 this가 print_this가 되는것이고,
printFunction()은 함수 자체가 글로벌하게 등록되어있기 때문에 글로벌(Window)에서 printFunction()을 호출하는것이다.
때문에 printFunction에서의 this가 Window가 되는것.
요약
javascript에서 this는 결국 누가 실행했느냐! 가 결정하는것
from http://kkamcoffee.tistory.com/241 by ccl(A) rewrite - 2021-09-07 03:01:18