[JS] ES6 - Functions

[JS] ES6 - Functions

이채현

Functions

Arrow Functions

기존 함수의 모습을 개선했다.

기존 함수

1
2
3
4
5
6
7
8
9
10
11
function Hello() {
return "hi";
}
console.log(Hello());

const names = ["kim", "lee", "park"];

const hearts = names.map(function (name) {
return name + " ❤️";
});
console.log(hearts);

Arrow Functions(1) - base

1
2
3
4
5
6
7
8
9
10
11
const Hello = () => {
return "hi";
};
console.log(Hello());

const names = ["kim", "lee", "park"];

const hearts = names.map((name) => {
return name + " ❤️";
});
console.log(hearts);

Arrow Functions(2) - implicit return

1
2
3
4
5
6
7
const Hello = () => "hi";
console.log(Hello());

const names = ["kim", "lee", "park"];

const hearts = names.map(name => name + " ❤️");
console.log(hearts);

this in Arrow Functions (Event listener in arrow function)

일반 콜백 함수안에서 this는 이벤트리스너에 연결 된 엘리먼트를 가리킨다. 하지만, arrow function안에서 this는 window를 가리킨다.

결론, this를 함수 안에 익명함수로 사용할 때는 Arrow Function이 아닌 일반 표준 funtion 형태로 사용해야한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const thisTest = {
cnt: 0,
addCnt() {
this.cnt++;
},
addCnt2: () => {
this.cnt++;
},
};
console.log(thisTest.cnt); // 0
thisTest.addCnt();
console.log(thisTest.cnt); // 1
thisTest.addCnt2;
console.log(thisTest.cnt); // 1

Default Values

1
2
3
4
5
6
const sayHi = (aName = "anon") => {
return `Hello ${aName}`;
}

console.log(sayHi());
console.log(sayHi('chaehyeon'));
Author

Chaehyeon Lee

Posted on

2022-01-01

Updated on

2022-06-26

Licensed under

댓글