기본 콘텐츠로 건너뛰기

12월, 2016의 게시물 표시

[javascript] arrow function VS function this binding

es6에서는 arrow function을 사용한다.  근데 arrow function과 일반 function은 엄연히 다르다. app.js 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 this.test  =   "global variable" ;   var  normalFunctionTest  =  {     test :  "mung" ,     c :  function (){          console .log(this.test);     } }   var  arrowFunctionTest  =  {     test :  "mung" ,     c : () = > {          console .log(this.test);     } }   normalFunctionTest.c(); arrowFunctionTest.c(); cs $ node app.js mung global variable https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions 가장 상단에 arrow function은 this를 바인딩 하지 않는다라고 설명이 되어있다. 그렇기 때문에 arrow function은 객체 메서드를 생성할 때 쓰지 않는 것이좋다. 문서를 보면 중간에 new와 함께 생성자로 사용하지 말라고 명시가 되어있다. Use of the new operator Arrow functions cannot be used as constructors and will throw an error when used with new. 이제 생성자에서 this 바인딩을 확인을