| ES6의 함수 구분 | constructor | prototype | super | arguments |
|---|---|---|---|---|
| 일반 함수 | O | O | X | O |
| 메서드 | X | X | O | O |
| 화살표 함수 | X | X | X | X |
메서드 : 축약 표현으로 정의된 함수
화살표 함수
26-28
class Prefixer {
constructor(prefix) {
this.prefix = prefix;
}
add(arr) {
// add 메서드는 인수로 전달된 배열 arr을 순회하며 배열의 모든 요소에 prefix를 추가한다.
return arr.map(function(item) {
return this.prefix + item; // this 바인딩되지 않아서 에러남
})
}
}
const prefixer = new Prefixer('-webkit-');
console.log(prefixer.add(['transition', 'user-select']))
콜백함수가 일반함수일 때 해결하는 방법 1)
26-29
class Prefixer {
constructor(prefix) {
this.prefix = prefix;
}
add(arr) {
const that = this;
return arr.map(function(item) {
return this.prefix + item;
})
}
}
콜백함수가 일반함수일 때 해결하는 방법 2)
26-30
class Prefixer {
constructor(prefix) {
this.prefix = prefix;
}
add(arr) {
const that = this;
return arr.map(function(item) {
return this.prefix + item;
}, this)
}
}
콜백함수가 일반함수일 때 해결하는 방법 3)
26-30
class Prefixer {
constructor(prefix) {
this.prefix = prefix;
}
add(arr) {
const that = this;
return arr.map(function(item) {
return this.prefix + item;
}.bind(this))
}
}
화살표 함수로 해결할 경우
class Prefixer {
constructor(prefix) {
this.prefix = prefix;
}
add(arr) {
return arr.map(item => this.prefix + item)
}
}
26-34
(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});
(참고한 사이트 : https://www.zerocho.com/category/JavaScript/post/57433645a48729787807c3fd)
this는 기본적으로 window
몇 가지 방법으로 window를 다른 것으로 바꿀 수 있음
call, apply, bind에서 첫 번째 인자로 다른 것을 넣어주는 게 this를 바꾸는 방법 중 하나
26-38
call / apply / bind
const add = (a, b) => a + b;
console.log(add.call(null, 1, 2));
console.log(add.apply(null, [1, 2]));
console.log(add.bind(null, 1, 2));
26-39
// Bad
const person = {
name: 'Lee',
sayHi: () => console.log(`Hi ${this.name}`)
}
// sayHi 프로퍼티에 할당된 화살표 함수 내부의 this는 상위 스코프인 전역의 this가 가리키는 전역 객체를 가리키므로
// 이 예제를 브라우저에서 실행하면 this.name은 빈 문자열을 갖는 window.name과 같다
// 전역 객체 window에는 빌트인 프로퍼티 name이 존재한다.
person.sayHi() // Hi
클래스 필드에 화살표 함수를 할당하여 프로퍼티로 사용할 수 있음
26-44
class Person {
// 클래스 필드 정의 제안
name = 'Lee';
sayHi = () => console.log(`Hi! ${this.name}`)
}
26-45
class Person {
constructor() {
this.name = 'Lee';
// 클래스가 생성한 인스턴스(this)의 sayHi 프로퍼티에 화살표 함수를 할당한다.
// 따라서 sayHi 프로퍼티는 인스턴스 프로퍼티다.
this.sayHi = () => console.log(`Hi! ${this.name}`)
}
}
26-45에서
this는 클래스 외부의 this를 참조하는게 아닌 인스턴스를 참조함
sayHi는 프로토타입 메서드가 아닌 인스턴스 메서드임
e. super
화살표 함수는 함수 자체의 super 바인딩을 갖지 않음 따라서, 화살표 함수 내에서 super를 참조하면 this와 마찬가지로 상위 스코프의 super를 참조
즉, constructor의 super 바인딩을 참조함
26-47
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?`;
}
/*
위의 내용은 사실 아래와 같은
class Derived extends Base {
constructor() {
sayHi = () => `${super.sayHi} how are you doing?`;
}
}
*/
const derived = new Derived('Lee');
console.log(derived.sayHi()); // Hi! Lee how are you doing?
f. arguments
화살표 함수는 함수 자체의 arguments 바인딩을 갖지 않음 상위 스코프의 arguments를 참조
26-48
(function() {
// 화살표 함수 foo의 arguments는 상위 스코프인 즉시 실행 함수의 arguments를 가리킴
const foo = () => console.log(arguments); // {'0': 1, '1': 2}
foo(3,4);
})(1,2);
// 화살표 함수 foo의 arguments는 상위 스코프 전역의 arguments를 가리킨다.
// 하지만 전역에는 argumemts 객체가 존재하지 않는다. arguments 객체는 함수 내부에서만 유효하다.
const foo = () => console.log(arguments);
foo(1,2); // ReferenceError
Rest 파라미터
나머지 매개변수를 나타날때
26-49
function foo(...rest) {
// 매개변수 rest는 인수들의 목록을 배열로 전달받는 Rest 파라미터다.
console.log(rest); // [1,2,3,4,5]
}
foo(1,2,3,4,5);
b. 일반 매개변수와 함께 사용 가능
26-50
function foo(param, ...rest) {
console.log(param); // 1
console.log(rest); // [2,3,4,5]
}
foo(1,2,3,4,5)
c. rest 파라미터는 반드시 마지막이여야 함
d. rest 파라미터는 한번만 선언 가능
e. 함수 객체의 length에 영향을 주지 않음
f. 일반함수, 메서드는 rest 파라미터와 arguments 객체 사용 가능 but, 화살표 함수는 arguments 객체를 갖지 않으므로 rest 파라미터를 사용해야함
매개변수 기본값
26-57
function sum(x,y) {
return x + y; // y가 undefined가 되어서 NaN이 됨
}
console.log(sum(1)); // NaN
그래서 기본값을 지정해줄수있음(rest 파라미터 사용할 경우 기본값을 지정할 수 없음)
26-59
function sum(x = 0, y = 0) {
return x + y;
}
console.log(sum(1,2)); // 3
console.log(sum(1)); //1
요즘에는 매개변수를 가져올때 undefined 이거나 null 을 거르는 연산자가 나옴
?? 연산자 (nullish coalesing)
참고 사이트: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing