const add = function(one, two){
return one + two;
};
log(add(1, 2));
const total = (one, two) => { // function 키워드 대신에 화살표 사용, => 양쪽에 공백 작성 가능
return one + two;
};
log(total(1, 2));
// 3
// 3
const total = (one, two) => one + two;
log(total(1, 2));
// 3
/*
함수 블록{}만 작성하면 undefined 반환
함수 블록에 return을 작성하지 않은 것과 같음
return을 작성하지 않으면 디폴트로 undefined를 반환
화살표 함수이기 때문이 아니라 JS 문법
*/
const total = (one) => {};
log(total(1));
// undefined
const point = (param) => ({book: param}); // 소괄호() 작성하지 않으면 undefined 반환
const result = point("책");
for (const key in result){
log(key + ": " + result[key]);
};
// book: 책
const get = param => param + 20;
log(get(10));
// 30
const get = () => 10 + 20;
log(get());
// 30
일반 함수를 전개하면 prototype과 constructor 있음
화살표 함수를 전개하면 prototype과 constructor 없음
prototype에 메소드를 연결하여 확장할 수 없음
prototype이 없으므로 그만큼 가볍
new 연산자로 인스턴스 생성 불가
arguments 사용 불가
arguments 대신에 rest 파라미터 사용
/*
1. strict 모드에서는 window.book()처럼 호출하는 함수 앞에 오브젝트를 작성해야 함.
이렇게 하지 않으면 book() 함수 안에서 this 값이 undefined
2. 또한, getPoint()처럼 window를 앞에 작성하지 않으면 getPoint() 안에서 this 값이 undefined
3. 이를 피하기 위해서 window.getPoint()로 호출하면 window 오브젝트에 getPoint()가 없으므로 에러
4. strict 모드의 함수에서 this를 참조하기 위해서는 this를 별도로 저장한 후 사용해야 하는데 번거롭
*/
"use strict"
function book(){
function getPoint(){
log(this);
};
getPoint();
//window.getPoint();
};
window.book();
//undefined
/*
1. 화살표 함수로 작성하면 getPoint() 호출 가능
2. 또한, getPoint()를 화살표 함수 안에서 this가 undefined가 아니라 글로벌(window) 오브젝트를 참조
3. var point = 100을 작성했으므로 100이 출력됨
*/
"use strict"
var point = 100;
function sports(){
const getPoint = () => {
log(this.point);
};
getPoint();
};
window.sports();
// 100
화살표 함수에서 정적 스코프의 this를 사용
정적(렉시컬Lexical) 스코프란
오브젝트에 바인딩된 스코프의 this를
/*
1. show() 화살표 함수에서 this가 window 오브젝트를 참조하는 것은
2. 함수 밖 스코프의 변수를 사용하듯이 show()의 스코프인 book 오브젝트에 설정된 스코프의 this를 화살표 함수에서 this로 사용하기 때문
3. book 오브젝트가 글로벌 오브젝트에 설정되므로 this가 window 오브젝트를 참조하게 됨
*/
var title = "책";
const book = {
show: () => log(this.title)
};
book.show();
// 책
인스턴스에서
prototype에 메소드 작성
var point = 200;
const Point = function(){
this.point = 100;
};
// prototype에 화살표 함수를 연결하면 함수 안에서 this가 글로벌 오브젝트를 참조
Point.prototype.getPoint = () => {
log(this.point);
};
new Point().getPoint();
// 200
/*
1. prototype에 일반 함수를 연결하고 함수 안에 화살표 함수를 작성한 형태
2. getPoint()가 일반 함수이므로 this가 생성한 인스턴스를 참조
3. 또한, 화살표 함수에서도 this가 생성한 인스턴스를 참조
4. 화살표 함수의 스코프인 getPoint()의 this를 사용하기 때문
*/
const Point = function(){
this.point = 100;
};
Point.prototype.getPoint = function(){
const add = () => this.point + 20;
log(add());
[1, 2].forEach((value) => {
log(this.point + value);
})
};
new Point().getPoint();
// 120
// 101
// 102
function 대신 =>를 사용, 함수 표현식 형태
화살표 함수에 this가 없다
메소드보다 함수로 사용하는 것이 효율성이 높음 (단독으로 사용)