
ES6에서는 기존의 함수에 몇 가지 새로운 기능과 스타일이 추가되었다. 이를 통해 기존보다 코드를 더 간결하게 작성하고 다양한 방식으로 활용할 수 있게 되었다. 지금부터 추가된 각 항목에 대해 정리해보자.
this 키워드를 사용해 해당 객체를 참조한다.function 키워드 대신 => 문법으로 작성하며, 일반 함수와this 바인딩이 다르게 동작한다.
function 키워드를 생략하여 바로 key() {...} 형식으로 선언한다.const person = {
name: "Sean",
sayHello() {
console.log(`Hello, I'm ${this.name}`);
},
};
person.sayHello(); // Hello, I'm Sean
this 키워드는 호출한 객체(person)을 가리킨다. => 문법을 사용하여 작성하는 함수로 더 간결한 구문을 제공한다.const arrow = (a, b) => { ... };
const arrow = a => { ... };
const arrow = () => { ... };
const power = a => a ** 2;
power(2); // 4
// 위 표현과 동일
const power = a => { return x ** 2; };
const create = (id, content) => ({ id, content });
create(1, 'Javascript'); // { id: 1, content: "Javascript" }
this를 가지지 않으며 화살표 함수 내부에서 this를 참조하면 상위 스코프의 this를 그대로 참조한다. 이를 lexical this라 한다.this가 함수가 정의된 위치에 의해 결정된다는 것을 의미한다.class Person {
constructor(lastName) {
this.lastName = lastName
}
firstName(arr) {
return arr.map(function(name) {
return this.lastName + name;
// TypeError: Cannot read property 'lastName' of undefined
});
}
}
const person1 = new Person('sean');
console.log(person1.firstName([' Kim', ' Lee']));
class Person {
constructor(lastName) {
this.lastName = lastName
}
firstName(arr) {
return arr.map(name => this.lastName + name);
}
}
const person1 = new Person('sean');
console.log(person1.firstName([' Kim', ' Lee']));
// ['sean Kim', 'sean Lee']
function add(...numbers) {
return numbers.reduce((sum, num) => sum + num, 0);
}
console.log(add(1, 2, 3, 4)); // 10
function num(a, b, ...rest) {
console.log(a) // 1
console.log(b) // 2
console.log(rest) // [3, 4, 5]
}
num(1, 2, 3, 4, 5);
...을 붙여서 사용한다.