25장 클래스
JS는 프로토타입 객체 지향언어라 클래스가 없었는데, 객체지향 프로그래머들의 진입장벽을 낳추기 위해 새로 도입했다고 한다.
기존 프로토타입 을 폐지하는 것인 아닌 클래스 패턴을 이용해서 프로토타입을 구현하는 느낌이다.
클래스는 생성자 함수보다 엄격하고 약간의 차이가 있다.
- 클래스를 new 연산자 없이 호출하면 에러 발생
- 상속을 지원하는
extends
와super
키워드 제공. - 클래스는 호이스팅이 발생하지 않는 것처럼 동작
- 클래스 내의 코드는 암묵적으로
strict mode
적용됨. - 클래스의 construcotr, 프로토타입 메서드, 정적 메서드는 모두 프로퍼티 어트리뷰트 [[Eunumerable]] 값이 false임. 즉, 열거되지 않음
클래스 정의
클래스 이름은 파스칼 케이스를 사용하는 것이 일반적.
클래스도 일급 객체이다.
클래스 몸체에서 정의할 수 있는 메서드는 constructor
, 프로토타입 메서드
, 정적 메서드
. 3가지 이다.
// 클래스 선언문
class Person {
// 생성자
constructor(name) {
// 인스턴스 생성 및 초기화
this.name = name; // name 프로퍼티는 public하다.
}
// 프로토타입 메서드
sayHi() {
console.log(`Hi! My name is ${this.name}`);
}
// 정적 메서드
static sayHello() {
console.log('Hello!');
}
}
// 인스턴스 생성
const me = new Person('Lee');
// 인스턴스의 프로퍼티 참조
console.log(me.name); // Lee
// 프로토타입 메서드 호출
me.sayHi(); // Hi! My name is Lee
// 정적 메서드 호출
Person.sayHello(); // Hello!
클래스 호이스팅
클래스는 함수로 평가됨.
// 클래스 선언문
class Person {}
console.log(typeof Person); // function
클래스 선언문으로 정의한 클래스는 소스평가 과정에서 평가되어 함수 객체를 생성한다.
클래스가 평가되어 생성된 함수 객체는 생성자 함수로 호출할 수 있는 constructor 이다.
constructor 니까 물론 이때 프로토타입도 더불어서 생성함.
클래스도 호이스팅이 발생하지만, let const 키워드로 선언한 변수처럼 호이스팅됨. 선언문 이전에는 일시적 사각지대에 빠져서 호이스팅이 발생하지 않는 것처럼 동작함.
const Person = '';
{
// 호이스팅이 발생하지 않는다면 ''이 출력되어야 한다.
console.log(Person);
// ReferenceError: Cannot access 'Person' before initialization
// 클래스 선언문
class Person {}
}
인스턴스 생성
클래스는 인스턴스를 생성하는 것이 유일한 존재이므로 반드시 new 연산자와 함께 호출해야함.
const Person = class MyClass {};
// 함수 표현식과 마찬가지로 클래스를 가리키는 식별자로 인스턴스를 생성해야 한다.
const me = new Person();
// 클래스 이름 MyClass는 함수와 동일하게 클래스 몸체 내부에서만 유효한 식별자다.
console.log(MyClass); // ReferenceError: MyClass is not defined
const you = new MyClass(); // ReferenceError: MyClass is not defined
메서드
앞서 말했던 것처럼 constructor, 프로토타입 메서드, 정적 메서드를 클래스 몸체에서 정의할 수 있다.
constructor
인스터스를 생성하고 초기화하기 위한 특수한 메서드
constructor 내부의 this는 생성자 함수와 마찬가지로 클래스가 생성한 인스턴스를 카리킨다.
// 클래스
class Person {
// 생성자
constructor(name) {
// 인스턴스 생성 및 초기화
this.name = name;
}
}
// 생성자 함수
function Person(name) {
// 인스턴스 생성 및 초기화
this.name = name;
}
클래스가 생성한 인스턴스에 constructor 메서드가 없음
왜 why?
constructor 메서드는 클래스가 평가되어 생성한 함수 객체 코드의 일부가 된다.
클래스 정의가 평가되면 constructor 메서드의 코드를 동작하는 함수 객체가 생성된다.
construcotr는 클래스 내에 한개만 존재할 수 있고, 생략할 수 있다.
생략하면 암묵적으로 빈 constructor가 정의된다.
class Person {
// constructor를 생략하면 다음과 같이 빈 constructor가 암묵적으로 정의된다.
constructor() {}
}
// 빈 객체가 생성된다.
const me = new Person();
console.log(me); // Person {}
constructor 에게 매개변수를 전달할면 인스턴스를 생성할 때 인자를 전달하면 된다.
class Person {
constructor(name, address) {
// 인수로 인스턴스 초기화
this.name = name;
this.address = address;
}
}
// 인수로 초기값을 전달한다. 초기값은 constructor에 전달된다.
const me = new Person('Lee', 'Seoul');
console.log(me); // Person {name: "Lee", address: "Seoul"}
new 연산과 함께 클래스가 호출되면 암묵적으로 this를 반환하는데, 다를 객체를 명시적으로 반환할 수 있다. 하지만 class 기본 동작을 훼손하기 때문에 사용하지 않는다.
class Person {
constructor(name) {
this.name = name;
// 명시적으로 객체를 반환하면 암묵적인 this 반환이 무시된다.
return {};
}
}
// constructor에서 명시적으로 반환한 빈 객체가 반환된다.
const me = new Person('Lee');
console.log(me); // {}
프로토타입 메서드
생성자 함수에서 프로토타입 메서드를 사용하기 위해서 명시적으로 추가해야하는 것과 달리, 클래스 몸체에서 정의한 메서드는 기본적으로 클래스의 프로토타입 메서드가 된다.
// 생성자 함수
function Person(name) {
this.name = name;
}
// 프로토타입 메서드
Person.prototype.sayHi = function () {
console.log(`Hi! My name is ${this.name}`);
};
class Person {
// 생성자
constructor(name) {
// 인스턴스 생성 및 초기화
this.name = name;
}
// 프로토타입 메서드
sayHi() {
console.log(`Hi! My name is ${this.name}`);
}
}
클래스도 마찬가지로 다음과 같은 프로토타입 체인을 형성한다.
정적 메서드
메서드에 static 키워드를 붙여서 메서드를 선언하면 정적 메서드가 된다.
class Person {
// 생성자
constructor(name) {
// 인스턴스 생성 및 초기화
this.name = name;
}
// 정적 메서드
static sayHi() {
console.log('Hi!');
}
}
정적 메서드와 프로토타입 메서드의 차이
- 정적 메서드와 프로토타입 메서드는 속해 있는 프로토타입 체인이 다르다.
- 정적 메서드는 클래스로 호출하고 프로토타입 메서드는 인스턴스로 호출
- 정적 메서드는 인스턴스 프로퍼티를 참조할 수 없지만, 프로토타입 메서드는 인스턴스 프로퍼티 참조 가능.
사실 다 당연한 얘기들이긴 한다.
this를 사용하지 않는 메서드는 정적 메서드로 정의하는 것이 좋다.
클래스의 인스턴스 생성 과정
-
인스턴스 생성과 this 바인딩
클래스로 인스턴스 생성하면, constructor 내부 코드가 실행되기 이전에 빈 객체를 생성하고, 이 객체가 인스턴스가 된다.
인스턴스의 프로토타입으로 클래스의 프로토 타입 객체를 설정한다
인스턴스를 this에 바인딩한다. -
인스턴스 초기화
constructor 내부 코드가 실행되면서 this에 바인딩 되어 있는 인스턴스를 초기화한다. -
인스턴스 반환
완성된 인스턴스가 바인딩된 this 반환
프로퍼티
인스턴스 프로퍼티
constructor 내부에서 this에 추가한 프로퍼티는 클래스가 생성한 인스턴스의 프로퍼티가 된다.
즉, 언제나 public하다. priviate한 프로퍼티를 정의하는 것은 현재 논의 중이라고 한다.
class Person {
constructor(name) {
// 인스턴스 프로퍼티
this.name = name; // name 프로퍼티는 public하다.
}
}
const me = new Person('Lee');
// name은 public하다.
console.log(me.name); // Lee
접근자 프로퍼티
getter 는 반드시 무언가를 반환해야하고, setter는 반드시 하나의 매개변수만 받을 수 있다.
class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
// fullName은 접근자 함수로 구성된 접근자 프로퍼티다.
// getter 함수
get fullName() {
return `${this.firstName} ${this.lastName}`;
}
// setter 함수
set fullName(name) {
[this.firstName, this.lastName] = name.split(' ');
}
}
const me = new Person('Ungmo', 'Lee');
// 데이터 프로퍼티를 통한 프로퍼티 값의 참조.
console.log(`${me.firstName} ${me.lastName}`); // Ungmo Lee
// 접근자 프로퍼티를 통한 프로퍼티 값의 저장
// 접근자 프로퍼티 fullName에 값을 저장하면 setter 함수가 호출된다.
me.fullName = 'Heegun Lee';
console.log(me); // {firstName: "Heegun", lastName: "Lee"}
// 접근자 프로퍼티를 통한 프로퍼티 값의 참조
// 접근자 프로퍼티 fullName에 접근하면 getter 함수가 호출된다.
console.log(me.fullName); // Heegun Lee
// fullName은 접근자 프로퍼티다.
// 접근자 프로퍼티는 get, set, enumerable, configurable 프로퍼티 어트리뷰트를 갖는다.
console.log(Object.getOwnPropertyDescriptor(Person.prototype, 'fullName'));
// {get: ƒ, set: ƒ, enumerable: false, configurable: true}
➕ Object.getOwnPropertyNames
는 비열거형을 포함한 모든 프로퍼티의 이름을 반환한다.
→ 접근자 프로퍼티도 나온다
// Object.getOwnPropertyNames는 비열거형(non-enumerable)을 포함한 모든 프로퍼티의 이름을 반환한다.(상속 제외)
Object.getOwnPropertyNames(me); // -> ["firstName", "lastName"]
Object.getOwnPropertyNames(Object.getPrototypeOf(me)); // -> ["constructor", "fullName"]
클래스 필드 정의 제안.
클래스 객체의 프로퍼티라고 이해했다.
나는 클래스 필드가 클래스로 만든 인스턴스들이 공통으로 사용하는 프로퍼티? 라고 생각했는데 생각해보니까 그건 프로토타입의 프로퍼티가 그 역할을 하고 있었다.
클래스 필드는 클래스가 생성할 인스턴스의 프로퍼티를 말한다.
class Person {
// 클래스 필드 정의
name = 'Lee';
}
const me = new Person();
console.log(me); // Person {name: "Lee"}
this는 클래스의 constructor 와 메서드 내에서만 유효하기 떄문에 클래스 필드에서 사용하면 안된다.
class Person {
// this에 클래스 필드를 바인딩해서는 안된다.
this.name = ''; // SyntaxError: Unexpected token '.'
}
클래스 필드 값을 참조하는 경우 this를 반드시 사용해서 참조해야한다.
그리고 constructor 에서 어차피 초기화할 거라면 클래스 필드를 정의할 필요가 없다.
class Person {
constructor(name) {
this.name = name;
}
}
const me = new Person('Lee');
console.log(me); // Person {name: "Lee"}
물론 클래스 필드에 함수를 할당할 수도 있지만, 인스턴스의 메서드가 되는 것이므로 권장하지는 않는다.
class Person {
// 클래스 필드에 문자열을 할당
name = 'Lee';
// 클래스 필드에 함수를 할당
getName = function () {
return this.name;
}
// 화살표 함수로 정의할 수도 있다.
// getName = () => this.name;
}
const me = new Person();
console.log(me); // Person {name: "Lee", getName: ƒ}
console.log(me.getName()); // Lee
private 필드 정의 제안
private 필드를 정의할 수 있는 사양이 논의중이라고 한다.
#
을 사용해서 private를 정의하고 접근한다.
private 필드는 클래스 내부에서만 참조할 수 있다. 즉, 외부에서 접근하려면 접근자 프로퍼티를 사용해서만 접근할 수 있다.
class Person {
// private 필드 정의
#name = '';
constructor(name) {
// private 필드 참조
this.#name = name;
}
}
const me = new Person('Lee');
// private 필드 \#name은 클래스 외부에서 참조할 수 없다.
console.log(me.\#name);
// SyntaxError: Private field '\#name' must be declared in an enclosing class
private 필드는 반드시 클래스 몸체에서 정의해줘야한다.
class Person {
constructor(name) {
// private 필드는 클래스 몸체에서 정의해야 한다.
this.#name = name;
// SyntaxError: Private field '\#name' must be declared in an enclosing class
}
}
static 필드 정의 제안
정적 메서드 처럼 static을 붙여서 정적 필드를 만들 수 있는 사양이 논의 중이라고 한다.
class MyMath {
// static public 필드 정의
static PI = 22 / 7;
// static private 필드 정의
static #num = 10;
// static 메서드
static increment() {
return ++MyMath.\#num;
}
}
console.log(MyMath.PI); // 3.142857142857143
console.log(MyMath.increment()); // 11
그렇게 치면 정적 메서드가 프로퍼티로 함수 할당한 거랑 뭐가 달라? 라는 생각도 든다. 사실 같은 일을 한다. 하지만 class를 class 답게 사용할 수 있게 만든 느낌이랄까. 물론 내생각이다.
상속에 의한 클래스 확장
클래스 상속과 생성자 함수 상속
상속에 의한 클래스 확장은 프로토타입 기반 상속과 다른 개념이다.
프로토타입 기반 상속은 프로토타입 체인을 통해서 다른 객체의 자산을 상속 받는 개념이지만, 상속에 의한 클래스 확장은 기존 클래스를 상속받아 클래스를 확장하여 정의하는 것이다.
Bird 클래스와 Lion 클래스는 상속을 통해서 Animal 클래스의 속성을 사용하면서 확장할 수 있다.
class Animal {
constructor(age, weight) {
this.age = age;
this.weight = weight;
}
eat() { return 'eat'; }
move() { return 'move'; }
}
// 상속을 통해 Animal 클래스를 확장한 Bird 클래스
class Bird extends Animal {
fly() { return 'fly'; }
}
const bird = new Bird(1, 5);
console.log(bird); // Bird {age: 1, weight: 5}
console.log(bird instanceof Bird); // true
console.log(bird instanceof Animal); // true
console.log(bird.eat()); // eat
console.log(bird.move()); // move
console.log(bird.fly()); // fly
- 프로토타입으로 흉내낼 수 있지만, 이젠 안씀
// 의사 클래스 상속(pseudo classical inheritance) 패턴 var Animal = (function () { function Animal(age, weight) { this.age = age; this.weight = weight; } Animal.prototype.eat = function () { return 'eat'; }; Animal.prototype.move = function () { return 'move'; }; return Animal; }()); // Animal 생성자 함수를 상속하여 확장한 Bird 생성자 함수 var Bird = (function () { function Bird() { // Animal 생성자 함수에게 this와 인수를 전달하면서 호출 Animal.apply(this, arguments); } // Bird.prototype을 Animal.prototype을 프로토타입으로 갖는 객체로 교체 Bird.prototype = Object.create(Animal.prototype); // Bird.prototype.constructor을 Animal에서 Bird로 교체 Bird.prototype.constructor = Bird; Bird.prototype.fly = function () { return 'fly'; }; return Bird; }()); var bird = new Bird(1, 5); console.log(bird); // Bird {age: 1, weight: 5} console.log(bird.eat()); // eat console.log(bird.move()); // move console.log(bird.fly()); // fly
extends 키워드
서브클래스(파생클래스, 자식 클래스) : 상속을 통해 확장된 클래스
수퍼클래스(베이스 클래스, 부모 클래스) : 서브클래스에서 상속된 클래스
extends 키워드가 수퍼클래스와 서브 클래스 간의 상속 관계를 설정해줌.
// 수퍼(베이스/부모)클래스
class Base {}
// 서브(파생/자식)클래스
class Derived extends Base {}
인스턴스의 프로토타입 체인 뿐만아니라 클래스끼리도 프로토타입 체인이 형성되어서 정적 메서드도 상속이 된다.
동적 상속
extends 키워드는 생성자 함수도 상속 받을 수 있음. 단, extends 키워드 앞에는 class 가 와야함
사실 extends 앞에는 [
[Construct]] 내부 메서드를 갖는 함수 객체로 평가될 수 있는 모든 표현식이 올 수 있음. 이를 이용해서 동적으로 상속받을 대상을 정할 수도 있음.
function Base1() {}
class Base2 {}
let condition = true;
// 조건에 따라 동적으로 상속 대상을 결정하는 서브클래스
class Derived extends (condition ? Base1 : Base2) {}
const derived = new Derived();
console.log(derived); // Derived {}
console.log(derived instanceof Base1); // true
console.log(derived instanceof Base2); // false
서브 클래스의 constructor
서브 클래스에서 constructor을 생략하면 암묵적으로 정의됨.
constructor(...args) { super(...args); }
즉, 클래스 호출할 때 전달할 인수를 가지고 다시 super를 호출한다.
super 키워드
super 키워드는 함수처럼 호출할 수도 있고, this와 같이 식별자처럼 참조할 수 있는 특수한 키워드다.
- super를 호출하면 수퍼클래스의 constructor를 호출
- super를 참조하면 수퍼클래스의 메서드를 호출할 수 있음
super 호출
// 수퍼클래스
class Base {
constructor(a, b) { // ④
this.a = a;
this.b = b;
}
}
// 서브클래스
class Derived extends Base {
constructor(a, b, c) { // ②
super(a, b); // ③
this.c = c;
}
}
const derived = new Derived(1, 2, 3); // ①
console.log(derived); // Derived {a: 1, b: 2, c: 3}
super 호출할 때 주의사항
- 서브클래스에서 constructor를 명시하는 경우 constructor내에서 반드시 super를 호출해야함.
- 서브클래스의 constrctor 에서 super를 호출하기 전에는 this를 참조할 수 없음.
- super를 서브클래스가 아닌 클래스의 constructor 나 함수에서 호출하면 에러 발생.
super 참조
super 참조를 통해서 수퍼클래스의 메서드를 참조하려면 수퍼클래스의 prototype 프로퍼티에 바인딩된 프로토타입을 참조할 수 있어야한다. ( 사실 당연한 말이다. )
// 수퍼클래스
class Base {
constructor(name) {
this.name = name;
}
sayHi() {
return `Hi! ${this.name}`;
}
}
class Derived extends Base {
sayHi() {
// __super는 Base.prototype을 가리킨다.
const __super = Object.getPrototypeOf(Derived.prototype);
return `${__super.sayHi.call(this)} how are you doing?`;
//return `${super.sayHi()}. how are you doing?`; 이 위와 같이 동작한다고 보면된다.
}
}
super로 호출되면 this는 부모의 prototype이 아닌 인스턴스를 가리킨다.
위 코드에서 Base.prototype를 찾기위해서 Derived.prototype을 따라올라가 찾는 모습이다. 즉, 메서드는 메서드가 super을 사용하기 위해서 메서드가 바인딩된 객체의 참조를 가지고 있어야한다.
그래서 내부슬롯 [[HomeObject]]를 가지며, 자신을 바인딩하고 있는 객체를 가르킨다.
super = Object.getPrototypeOf([[HomeObject]])
이런 느낌으로 보면됨.
프로퍼티로 정의된 함수는 super을 참조할 수 없다.
➕ 클래스에서 뿐만 아니라 객체 리터럴에서도 super참조를 사용할 수 있다. 마찬가지로 축약표현 메서드에서만 가능
const base = {
name: 'Lee',
sayHi() {
return `Hi! ${this.name}`;
}
};
const derived = {
__proto__: base,
// ES6 메서드 축약 표현으로 정의한 메서드다. 따라서 [[HomeObject]]를 갖는다.
sayHi() {
return `${super.sayHi()}. how are you doing?`;
}
};
console.log(derived.sayHi()); // Hi! Lee. how are you doing?
서브 클래스의 정적 메서드에서 super는 수퍼클래스를 가르킴
// 수퍼클래스
class Base {
static sayHi() {
return 'Hi!';
}
}
// 서브클래스
class Derived extends Base {
static sayHi() {
// super.sayHi는 수퍼클래스의 정적 메서드를 가리킨다.
return `${super.sayHi()} how are you doing?`;
}
}
console.log(Derived.sayHi()); // Hi! how are you doing?
처음에 조금 헷갈렸다. super는 프로토타입 객체를 가르키는데, derived의 prototype은 Base 의 프로토타입 객체라 아니라 Base다. 즉 Derived의 sayHi 에서 super는 Base를 가르킨다.
만약 Derived에 sayHi2 라는 메서드가 있다면(정적 메서드 X) 그 안에서 super은 Base의 프로토타입 객체를 가르키게 된다. 그것이 인스턴스니까.
상속 클래스의 인스턴스 생성과정
// 수퍼클래스
class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
getArea() {
return this.width * this.height;
}
toString() {
return `width = ${this.width}, height = ${this.height}`;
}
}
// 서브클래스
class ColorRectangle extends Rectangle {
constructor(width, height, color) {
super(width, height);
this.color = color;
}
// 메서드 오버라이딩
toString() {
return super.toString() + `, color = ${this.color}`;
}
}
const colorRectangle = new ColorRectangle(2, 4, 'red');
console.log(colorRectangle); // ColorRectangle {width: 2, height: 4, color: "red"}
// 상속을 통해 getArea 메서드를 호출
console.log(colorRectangle.getArea()); // 8
// 오버라이딩된 toString 메서드를 호출
console.log(colorRectangle.toString()); // width = 2, height = 4, color = red
-
서브 클래스의 super 호출
클래스는 내부슬롯 [[ConstructorKind]]를 가지고 수퍼클래스면 ‘base’, 서브클래스면 ‘dervied’ 값을 가진다. JS엔진이 클래스를 평가할 때 이 내부슬롯의 따라서 new 연산자 호출에 대한 동작이 달라진다.
서브클래스는 자신이 직접 인스턴스를 생성하지 않고 수퍼클래스에게 인스턴스 생성을 위임한다. 그래서 constructor 에서 반드시 super을 호출해야한느 것. -
수퍼 클래스의 인스턴스 생성과 this 바인딩
수퍼클래스의 constructor 내부 코드 실행되기 전에 빈 객체 생성하고 이 객체가 바로 클래스가 생성한 인스턴스임. 이 객체가 this 에 바인딩 된다.이 인스턴스는 수퍼클래스가 생성한 것이지만, new 연산자와 호출된 클래스가 서브클래스이기 때문에, new.target 은 서브 클래스를 가리킨다. 그래서 인스턴스는 new.target 이 가리키는 서브클래스가 생성한 것으로 처리된다.
즉, 인스턴스의 프로토타입은 수퍼클래스의 프로토타입객체라 아니라, 서브클래스의 프로토타입 객체가 된다.
-
수퍼클래스의 인스턴스 초기화
// 수퍼 클래스의 인스턴스 생성과 This 바인딩
class Rectangle {
constructor(width, height) {
// 암묵적으로 빈 객체, 즉 인스턴스가 생성되고 this에 바인딩된다.
console.log(this); // ColorRectangle {}
// new 연산자와 함께 호출된 함수, 즉 new.target은 ColorRectangle이다.
console.log(new.target); // ColorRectangle
// 생성된 인스턴스의 프로토타입으로 ColorRectangle.prototype이 설정된다.
console.log(Object.getPrototypeOf(this) === ColorRectangle.prototype); // true
console.log(this instanceof ColorRectangle); // true
console.log(this instanceof Rectangle); // true
// 인스턴스 초기화
this.width = width;
this.height = height;
console.log(this); // ColorRectangle {width: 2, height: 4}
}
...
```
-
서브 클래스 constructor로의 복귀와 this 바인딩
super호출 종료되고 제어 흐름이 서브클래스로 constructor 로 돌아온다. 이때 super가 반환한 인스턴스가 this에 바인딩 된다. 서브클래스는 인스턴스 생성하지 않고 super 가 반환한 인스턴스 그대로 사용함.
⇒ super 호출전에 this 참조할 수 없는 이유 -
서브 클래스의 인스턴스 초기화
-
인스턴스 반환
클래스의 모든 처리 끝나고 바인딩된 this가 반환
ㅅ// 4,5,6번
class ColorRectangle extends Rectangle {
constructor(width, height, color) {
super(width, height);
// super가 반환한 인스턴스가 this에 바인딩된다.
console.log(this); // ColorRectangle
// 인스턴스 초기화
this.color = color;
// 완성된 인스턴스가 바인딩된 this가 암묵적으로 반환된다.
console.log(this); // ColorRectangle {width: 2, height: 4, color: "red"}
}
...
```
표준 빌트인 생성자 함수 확장
String, Number, Array 같은 표준 빌트인 객체도 extends 키워드를 사용해서 확장할 수 있음.
// Array 생성자 함수를 상속받아 확장한 MyArray
class MyArray extends Array {
// 중복된 배열 요소를 제거하고 반환한다: [1, 1, 2, 3] => [1, 2, 3]
uniq() {
return this.filter((v, i, self) => self.indexOf(v) === i);
}
// 모든 배열 요소의 평균을 구한다: [1, 2, 3] => 2
average() {
return this.reduce((pre, cur) => pre + cur, 0) / this.length;
}
}
const myArray = new MyArray(1, 1, 2, 3);
console.log(myArray); // MyArray(4) [1, 1, 2, 3]
// MyArray.prototype.uniq 호출
console.log(myArray.uniq()); // MyArray(3) [1, 2, 3]
// MyArray.prototype.average 호출
console.log(myArray.average()); // 1.75
이런 식으로 확장해서 사용할 수 있는데, filter로 반환해는 객체가 Array 인스턴스가 아닌 MyArray의 인스턴스가 된다.
Array 인스턴스로 반화하게 하려면 Symbo.species
사용해서 정적 접근자 프로퍼티 추가해야한다.
// Array 생성자 함수를 상속받아 확장한 MyArray
class MyArray extends Array {
// 모든 메서드가 Array 타입의 인스턴스를 반환하도록 한다.
static get [Symbol.species]() { return Array; }
// 중복된 배열 요소를 제거하고 반환한다: [1, 1, 2, 3] => [1, 2, 3]
uniq() {
return this.filter((v, i, self) => self.indexOf(v) === i);
}
// 모든 배열 요소의 평균을 구한다: [1, 2, 3] => 2
average() {
return this.reduce((pre, cur) => pre + cur, 0) / this.length;
}
}
const myArray = new MyArray(1, 1, 2, 3);
console.log(myArray.uniq() instanceof MyArray); // false
console.log(myArray.uniq() instanceof Array); // true
// 메서드 체이닝
// uniq 메서드는 Array 인스턴스를 반환하므로 average 메서드를 호출할 수 없다.
console.log(myArray.uniq().average());
// TypeError: myArray.uniq(...).average is not a function