ES6 이전의 모든 함수는 일반 함수로서 호출할 수 있는 것은 물론 생성자 함수로서 호출할 수 있다.
ES6에서는 함수를 사용 목적에 따라 세 가지 종류로 명확히 구분한다.
const obj = {
x: 1,
// foo는 메서드이다.
foo() { return this.x; },
// bar에 바인딩된 함수는 메서드가 아닌 일반 함수이다.
bar: function() { return this.x; }
};
console.log(obj.foo()); // 1
console.log(obj.bar()); // 1
const base = {
name: 'Lee',
sayHi() {
return `Hi! ${this.name}`;
}
};
const derived = {
__proto__: base,
// sayHi는 ES6 메서드다. ES6 메서드는 [[HomeObject]]를 갖는다.
// sayHi의 [[HomeObject]]는 sayHi가 바인딩된 객체인 derived를 가리키고
// super는 sayHi의 [[HomeObject]]의 프로토타입인 base를 가리킨다.
sayHi() {
return `${super.sayHi()}. how are you doing?`;
}
};
console.log(derived.sayHi()); // Hi! Lee. how are you doing?
const multiply = (x, y) => x * y;
multiply(2, 3); // -> 6
const arrow = x => { ... };
const arrow = () => { ... };
// concise body
const power = x => x ** 2;
power(2); // -> 4
// 위 표현은 다음과 동일하다.
// block body
const power = x => { return x ** 2; };
const arrow = () => const x = 1; // SyntaxError: Unexpected token 'const'
// 위 표현은 다음과 같이 해석된다.
const arrow = () => { return const x = 1; };
const create = (id, content) => ({ id, content });
create(1, 'JavaScript'); // -> {id: 1, content: "JavaScript"}
// 위 표현은 다음과 동일하다.
const create = (id, content) => { return { id, content }; };
const Foo = () => {};
// 화살표 함수는 생성자 함수로서 호출할 수 없다.
new Foo(); // TypeError: Foo is not a constructor
const arrow = (a, a) => a + a;
// SyntaxError: Duplicate parameter name not allowed in this context
class Prefixer {
constructor(prefix) {
this.prefix = prefix;
}
add(arr) {
return arr.map(item => this.prefix + item);
}
}
const prefixer = new Prefixer('-webkit-');
console.log(prefixer.add(['transition', 'user-select']));
// ['-webkit-transition', '-webkit-user-select']
class Person {
constructor() {
this.name = 'Lee';
// 클래스가 생성한 인스턴스(this)의 sayHi 프로퍼티에 화살표 함수를 할당한다.
// sayHi 프로퍼티는 인스턴스 프로퍼티이다.
this.sayHi = () => console.log(`Hi ${this.name}`);
}
}
sayHi 클래스 필드에 할당한 화살표 함수의 상위 클래스는 클래스 외부이다. 하지만 this는 클래스 외부를 참조하지 않고 생성할 인스턴스를 참조한다 따라서 sayHi 클래스 필드에 할당한 화살표 함수 내부에서 참조한 this 는 constructor 내부의 this 바인딩과 같다.
class Base {
constructor(name) {
this.name = name;
}
sayHi() {
return `Hi! ${this.name}`;
}
}
class Derived extends Base {
// 화살표 함수의 super는 상위 스코프인 constructor의 super를 가리킨다.
sayHi = () => `${super.sayHi()} how are you doing?`;
}
const derived = new Derived('Lee');
console.log(derived.sayHi()); // Hi! Lee how are you doing?
(function () {
// 화살표 함수 foo의 arguments는 상위 스코프인 즉시 실행 함수의 arguments를 가리킨다.
const foo = () => console.log(arguments); // [Arguments] { '0': 1, '1': 2 }
foo(3, 4);
}(1, 2));
// 화살표 함수 foo의 arguments는 상위 스코프인 전역의 arguments를 가리킨다.
// 하지만 전역에는 arguments 객체가 존재하지 않는다. arguments 객체는 함수 내부에서만 유효하다.
const foo = () => console.log(arguments);
foo(1, 2); // ReferenceError: arguments is not defined
function foo(param, ...rest) {
console.log(param); // 1
console.log(rest); // [ 2, 3, 4, 5 ]
}
foo(1, 2, 3, 4, 5);
function bar(param1, param2, ...rest) {
console.log(param1); // 1
console.log(param2); // 2
console.log(rest); // [ 3, 4, 5 ]
}
bar(1, 2, 3, 4, 5);
function foo(...rest1, ...rest2) { }
foo(1, 2, 3, 4, 5);
// SyntaxError: Rest parameter must be last formal parameter
function sum(...args) {
// Rest 파라미터 args에는 배열 [1, 2, 3, 4, 5]가 할당된다.
return args.reduce((pre, cur) => pre + cur, 0);
}
console.log(sum(1, 2, 3, 4, 5)); // 15
function sum(x = 0, y = 0) {
return x + y;
}
console.log(sum(1, 2)); // 3
console.log(sum(1)); // 1