on
[Javascript] Arrow function vs Function
[Javascript] Arrow function vs Function
Arrow function은 function과 동일한 개념이 아니다.
Arrow function과 function의 차이점은 this
Arrow Function은 this 바인딩을 갖지 않는다. 기존의 function은 this의 탐색 범위가 함수의 {} 안인 찾은 반면 Arrow Function에서 this는 일반적인 인자/변수와 동일하게 취급된다.
function에서 this는 함수를 호출한 객체의 this를 가리킴
Arrow function에서 this는 상위 scope의 this를 가리킴 -> Lexical this
function example
// function(){}방식으로 호출할 때 function objFunction() { console.log('Inside `objFunction`:', this.foo); return { foo: 25, bar: function() { console.log('Inside `bar`:', this.foo); }, }; } objFunction.call({foo: 13}).bar(); // objFunction의 `this`를 오버라이딩합니다.
result
Inside `objFunction`: 13 // 처음에 인자로 전달한 값을 받음 Inside `bar`: 25 // 자신이 있는 Object를 this로 인지해서 25를 반환
Arrow function example
// Arrow Function방식으로 호출할 때 function objFunction() { console.log('Inside `objFunction`:', this.foo); return { foo: 25, bar: () => console.log('Inside `bar`:', this.foo), }; }
result
Inside `objFunction`: 13 // 처음에 인자로 전달한 값을 받음 Inside `bar`: 13 // Arrow Function에서 this는 일반 인자로 전달되었기 때문에 이미 값이 13로 지정됩니다.
출처
https://beomi.github.io/2017/07/12/understanding_js_scope_function_vs_arrow/
from http://iwant2free.tistory.com/37 by ccl(A) rewrite - 2021-10-31 10:02:07