javascript 화살표함수 특징 6 _191202
TILarrow Function
this
,arguments
,super
, ornew.target
키워드에 바인딩이 없다.
화살표 함수는 항상 익명입니다.
이 함수 표현은 메소드 함수가 아닌 곳에 가장 적합합니다.
그래서 생성자로서 사용할 수 없습니다.
구문
// 객체 리터럴 표현을 반환하기 위해서는 함수 본문(body)을 괄호 속에 넣음:
params => ({foo: bar})
/*구문 예시*/
var materials = [
'Hydrogen',
'Helium',
'Lithium',
'Beryllium'
];
// 화살표 함수를 이용해 아래와 같이 표현할 수 있다
materials.map((material) => {
return material.length;
}); // [8, 6, 7, 9]
// 매개변수 목록 내 비구조화도 지원됨
materials.map(({length}) => length); // [8, 6, 7, 9]
** this 간단 정리
: 생성자 함수와 객체의 메소드를 제외한 모든 함수(내부 함수, 콜백 함수 포함) 내부의 this는 전역 객체
1. Arrow Function 에서 this
An arrow function does not have its own this
. The this
value of the enclosing lexical scope is used; arrow functions follow the normal variable lookup rules. So while searching for this
which is not present in current scope, an arrow function ends up finding the this
from its enclosing scope.
화살표 함수는 자기 this 가 없다.
화살표 함수 내부에서 사용된 this는 상위체인의 범위에서 찾는다(감싸고 있는 렉시컬 스코프).
화살표함수도 일반적인변수 찾는 룰 처럼 this를 찾을때까지 enclosing scope 를 타고 올라간다.
메소드로 사용될 때
var obj = {
i: 10,
b: () => console.log(this.i, this),
c: function() {
console.log(this.i, this);
}
}
obj.b(); // prints undefined, Window {...} (or the global object)
obj.c(); // prints 10, Object {...}
화살표 함수는 자신의 this를 가지고("bind" 바인드)있지 않습니다.
그래서 obj.b 의 this 는 window
* ES6에서는 메소드를 선언할 때, function 키워드를 생략한 축약 표현을 사용할 수 있다.
const person = {
name: 'Lee',
sayHi() { // === sayHi: function() {
console.log(`Hi ${this.name}`);
}
};
Arrow Function 에서 call, apply 의 this argument 는 무시된다. (this 가 없으니까)
var adder = {
base: 1,
add: function(a) {
var f = v => v + this.base;
return f(a);
},
addThruCall: function(a) { //(2) a에 1이 들어간다.
var f = v => v + this.base; //함수를 화살표함수로 정의
var b = { //변수 정의
base: 2
};
return f.call(b, a); //(3) call에 this, paramenter 를 담아서 실행한다. f(1) 과 같은 결과임
//-> 1 + 1 =2, 즉 b라는 객체를 this로 넘겨도 무시함 두번째 인자로 받은 변수만 적용한다.
}
};
console.log(adder.add(1)); // This would log 2
console.log(adder.addThruCall(1)); // This would log 2 still (1) 호출 (4) 결과값 2
Since arrow functions do not have their own this
, the methods call()
and apply()
can only pass in parameters. Any this
argument is ignored.
2. 화살표 함수는 생성자로서 사용될 수 없으며 new
와 함께 사용하면 오류가 발생합니다.
3. 화살표 함수는 prototype
속성이 없습니다.
4. yield
키워드는 화살표 함수의 본문(그 안에 더 중첩된 함수 내에서 허용한 경우를 제외하고)에 사용될 수 없습니다. 그 결과, 화살표 함수는 생성기(generator)로서 사용될 수 없습니다. <- ㅁ
5. 바인딩 되지 않는 arguments
화살표 함수는 arguments
객체를 바인드 하지 않습니다.
function foo(n) {
var f = () => console.log(arguments);//foo's implicit arguments binding. arguments[0] is n
return f();
}
foo(4);
//내부 화살표함수 f 에서 arguments는
//foo(4) 가 실행되면서 넘어온 n 값인 4 를 arguments로 받음.(화살표함수 당사자의 인자는 없음에도 불구하고)
화살표 함수는 자신의 arguments
객체가 없지만, 대부분의 경우에 나머지 매개변수가 좋은 대안입니다
function foo(n) {
var f = (...args) => args[0] + n; ///args = [2]
//:foo 실행시 들어오는 n 과 관계없이 return f(2) 의 2값을 받는다.
return f(2);
}
foo(1); // 3
6. addEventListener 함수의 콜백 함수
addEventListener 함수의 콜백 함수를 화살표 함수로 정의하면 this가 상위 컨택스트인 전역 객체 window를 가리킨다.
따라서 addEventListener 함수의 콜백 함수 내에서 this를 사용하는 경우, function 키워드로 정의한 일반 함수를 사용하여야 한다. 일반 함수로 정의된 addEventListener 함수의 콜백 함수 내부의 this는 이벤트 리스너에 바인딩된 요소(currentTarget)를 가리킨다.
참고 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
'TIL' 카테고리의 다른 글
react - class, JSX 콜백함수에서 this (0) | 2019.12.03 |
---|---|
react - 이벤트 핸들러에 인수 전달하기 (0) | 2019.12.03 |
딥카피 만드는 함수 (0) | 2019.12.02 |
191201 어제의 충격 포인트 indexOf (0) | 2019.12.02 |
TIL _ node.js & express & mongoDB (0) | 2019.12.01 |