// ES6 이전의 모든 함수는 callable이면서 constructor였다
var foo = function () {
return 1;
};
// 일반함수
foo(); // → 1
// 생성자 함수로서 호출
new foo(); // → foo {}
// 메서드로서 호출
var obj = { foo: foo };
obj.foo(); // → 1
문제점
- 객체에 바인딩된 함수를 생성자 함수로 호출 가능하다.
- 콜백 함수도 생성자 함수로 호출이 가능하다.
- 이런 함수들은 prototype 프로퍼티를 갖고 불필요한 프로토타입 객체를 생성하여 성능을 떨어뜨린다.
| ES6 함수의 구분 | constructor | prototype | super | arguments |
|---|---|---|---|---|
| 일반함수 | O | O | X | O |
| 메서드 | X | X | O | O |
| 화살표 함수 | X | X | X | X |
😂외울게 늘었다.
const obj = {
x: 1,
// 메서드로 정의
foo () { return this.x; }
// 일반 함수처럼 정의
bar: function () { return this.x;}
};
console.log(obj.foo()); // 1
console.log(obj.bar()); // 1
// ES6의 메서드는 생성자 함수로써 호출 불가
new obj.foo(); // -> TypeError: obj.foo is not a constructor
new obj.bar(); // -> bar{}
참고 : 표준 빌트인 객체가 제공하는 프로토타입 메서드와 정적 메서드는 모두 non-constructor
String.prototype.toUpperCase.prototype; // -> undefined
String.fromCharCode.prototype; // -> undefined
Number.prototype.toFixed.prototype; // -> undefined
Number.isFinite.prototype; // -> undefined
Array.prototype.map.prototype; // -> undefined
Array.from.prototype; // -> undefined
const multiply = (x, y) => x * y;
multiply(2,3); // -> 6
// 매개변수의 개수에 따라 다음과 같은 형태로 사용 가능
const arrow = (x, y) => { ... };
const arrow = x => { ... }; // 하나라면 소괄호 생략 가능
const arrow = () => { ... }; // 매개변수가 없다면 소괄호 생략 불가능
// 함수 몸체의 중괄호는 경우에 따라 생략 가능
const power = x => x ** 2; // 몸체가 하나의 표현식인 문이라면 중괄호 생략 가능
const power = x => { return x ** 2;};
power(2); // -> 4
// 표현식이 아닌 문은 오류 발생
const arrow = () => const x = 1; // SyntaxError: Unexpected token 'const'
const arrow = () => {return const x = 1;}; // 이렇게 해석되기 때문
// 객체 리터럴 반환시, 객체 리터럴을 소괄호()로 감싸주어야 한다. 이 규칙이 매번 가장 기억안남🤬
const create = (id, content) => ({id, content});
const create = (id, content) => { return { id, content };}; // 위 아래 동일
create(1, 'JavaScript');
// 소괄호로 감싸지 않는다면?
const create = (id, content) => {id, content}; // 그냥 이렇게 생긴 그대로 해석하고 return은 안붙여준다.
// 즉시 실행 함수로 사용 가능
const person = (name => ({
sayHi() { return `Hi? My name is ${name}.`;}
}))('Lee');
console.log(person.sayHi());
// ES5
[1,2,3].map(function (v) {
return v * 2;
});
// ES6
[1,2,3].map(v => v * 2); // -> [2, 4, 6]
// 중첩 함수 foo의 상위 스코프는 즉시 실행 함수다.
// 따라서 화살표 함수 foo의 this는 상위 스코프인 즉시 실행 함수의 this를 가리킨다.
(function() {
const foo = () => console.log(this);
foo();
}.call({ a: 1 })); // {a: 1}
// bar 함수는 화살표 함수를 반환한다.
// bar 함수가 반환한 화살표 함수의 상위 스코프는 화살표 함수 bar다.
// 하지만 화살표 함수는 함수 자체의 this 바인딩을 갖지 않으므로 bar 함수가 반환한
// 화살표 함수 내부에서 참조하는 this는 화살표 함수가 아닌 즉시 실행 함수의 this를 가리킨다.
(function() {
const bar = () => () => console.log(this);
bar()();
}.call({ a: 1 })); // { a: 1}
// increase 프로퍼티에 할당한 화살표 함수의 상위 스코프는 전역
// 따라서 increase 프로퍼티에 할당한 화살표 함수의 this는 전역 객체를 가리킨다.
const counter = {
num: 1,
increase: () => ++this.num
};
console.log(counter.increase()); // NaN
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); // 3,4 무시됨
} (1,2)); // 얠 가져옴
// 전역에는 arguments 객체가 없다. 따라서 에러
const foo = () => console.log(arguments);
foo(1,2); // ReferenceError: arguments is not defined
function foo(...rest) {
// 매개변수 rest는 인수들의 목록을 배열로 전달받는 Rest 파라미터
console.log(rest); // [1,2,3,4,5]
}
foo(1,2,3,4,5);
// 매개변수와 Rest는 같이 사용 가능. 인수는 매개변수와 Rest 파라미터에 순차적으로 할당된다.
function foo(param1, param2, ...rest) {
console.log(param1); // 1
console.log(param2); // 2
console.log(rest); // [3,4,5]
}
foo(1,2,3,4,5);
// Rest는 반드시 마지막 파라미터어야 한다
function foo(...rest, param1, param2){}
foo(1,2,3,4) // SyntaxError
// Rest는 단 하나만 가능
function foo(...rest1, ...rest2){}
foo(1,2,3,4) // SyntaxError
// 함수 length 프로퍼티와 무관
function foo(...rest) {}
console.log(foo.length); // 0
function foo(a,b,c,...rest) {}
console.log(foo.length); // 3
// arguments의 경우
function sum() {
var array = Array.prototype.slice.call(arguments);
return array.reduce(function (pre, cur) {
return pre + cur;
}, 0);
}
console.log(sum(1,2,3,4,5)); // 15
// Rest의 경우
function sum(...args) {
return args.reduce((pre, cur) => pre + cur, 0);
}
console.log(sum(1,2,3,4,5)); // 15
화살표 함수는 arguments 객체가 바인딩되어 있지 않다. 대신 Rest 파라미터는 지원한다.
// 매개변수가 모자라면 1 + undefined = NaN
function sum(x,y) {
return x + y;
}
console.log(sum(1)); // NaN
function sum(x = 0, y = 0) {
return x + y;
}
console.log(sum(1,2)); // 3
console.log(sum(1)); // 1
function sum(x, y = 1, z = 1) {
console.log(arguments);
}
console.log(sum.length); // 1
function sum(x, y, z = 1) {
console.log(arguments);
}
console.log(sum.length); // 2
function foo(...rest = []) {
console.log(rest);
}
// SyntaxError