-
[Javascript] Class (2) 인스턴스, 추가 기능, 상속사부작사부작/Javascript 2022. 4. 4. 23:59
#모던자바스크립트_딥다이브 스터디를 진행하면서 정리한 내용입니다.
클래스의 인스턴스 생성 과정
class Person { // 생성자 constructor(name) { // 1. 암묵적으로 인스턴스가 생성되고 this에 바인딩된다. console.log(this); // Person {} console.log(Object.getPrototypeOf(this) === Person.prototype); // true // 2. this에 바인딩되어 있는 인스턴스를 초기화한다. this.name = name; // 3. 완성된 인스턴스가 바인딩된 this가 암묵적으로 반환된다. } }
1. 인스턴스 생성과 this 바인딩
1) new 연산자와 함께 클래스를 호출하면 클래스 안의 constructor의 코드가 실행되기에 앞서 암묵적으로 빈 객체가 생성된다. 이 객체가 클래스가 생성한 인스턴트다.
2) 인스턴스의 프로토타입으로 클래스의 prototype 프로퍼티가 가리키는 객체가 설정된다.
3) 인스턴스는 this에 바인딩된다. 따라서 constructor 내부의 this는 클래스가 생성한 인스턴스를 가리킨다.
2. 인스턴스 초기화
constructor 내부 코드가 실행되어 this에 바인딩되어 있는 인스턴스를 초기화한다. 즉, 인스턴스에 프로퍼티를 추가하고 constuctor가 인수로 전달받은 초기값으로 인스턴스의 프로퍼티 값을 초기화한다. 만약 constructor가 생략되었다면 이 과정도 생략된다.
3. 인스턴스 반환
인스턴스가 바인딩된 this가 암묵적으로 반환된다.
프로퍼티
1. 인스턴스 프로퍼티
constructor 내부의 this에는 이미 클래스가 암묵적으로 생성한 인스턴스인 빈 객체가 바인딩되어 있다. 따라서 인스턴스의 프로퍼티는 constructor 내부에서 정의해야 한다.
class Person { constructor(name) { // 인스턴스 프로퍼티 this.name = name; } } const me = new Person('Lee'); console.log(me); // Person {name: "Lee"}
constructor 내부에서 this에 추가한 프로퍼티는 언제나 클래스가 생성한 인스턴스의 프로퍼티가 된다. 인스턴스 프로퍼티는 언제나 public하다.
2. 접근자 프로퍼티
접근자 프로퍼티는 자체적으로는 값([[Value]])를 갖지 않고 다른 데이터 프로퍼티의 값을 읽거나 저장할 때 사용하는 접근자 함수로 구성된 프로퍼티다. 접근자 함수는 getter 함수와 setter 함수로 구성되어 있다.
- getter: getter는 인스턴스 프로퍼티에 접근할 때마다 프로퍼티 값을 조작하거나 별도의 행위가 필요할 때 사용한다. 즉, 어떠한 값을 취득할 때 사용하므로 반드시 무언가를 반환해야 한다. getter는 메서드 앞에 get 키워드를 사용해 정의한다.
- setter: setter는 인스턴스 프로퍼티에 값을 할당할 때마다 프로퍼티 값을 조작하거나 별도의 행위가 필요할 때 사용한다. 즉, 무언가를 프로퍼티에 할당해야 할 때 사용하므로 반드시 매개변수가 있어야한다. setter는 단 하나의 값만 할당받기 때문에 단 하나의 매개변수만 선언할 수 있다. setter는 메서드 이름 앞에 set 키워드를 사용해 정의한다.class Person { constructor(firstName, lastName) { this.firstName = firstName; this.lastName = lastName; } // 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 console.log(Object.getOwnPropertyDescriptor(Person.prototype, 'fullName')); // {get: ƒ, set: ƒ, enumerable: false, configurable: true}
클래스의 메서드는 기본적으로 프로토타입 메서드가 된다. 따라서 클래스의 접근자 프로퍼티 또한 인스턴스의 프로퍼티가 아닌 프로토타입의 프로퍼티가 된다.
3. 클래스 필드 정의 제안(Chrome 72이상, Node.js 버전 12이상)
클래스 필드란 클래스가 생성할 인스턴스의 프로퍼티를 가리킨다. 자바스크립트의 클래스 몸체에는 메서드만 선언할 수 있다. 클래스 몸체에 프로퍼티를 선언하면 에러가 발생한다. 다만 Chrome72, Node.js 12 버전 이상에서는 클래스 필드를 지원하여 에러가 발생하지 않는다.
class Person { // 클래스 필드 정의 => 원래는 에러가 나야한다. name = 'Lee'; } const me = new Person(); console.log(me); // Person {name: "Lee"}
자바스크립트의 클래스 필드는 아래와 같은 특징을 갖는다.
1) 클래스 몸체에서 클래스 필드를 정의하는 경우 this에 클래스 필드를 바인딩해서는 안 된다. this는 클래스 constructor에서만 유효하다.
class Person { // this에 클래스 필드를 바인딩해서는 안된다. this.name = ''; // SyntaxError: Unexpected token '.'
2) constructor나 메서드에서 클래스 필드를 참조하는 경우, this를 반드시 사용해야 한다.
class Person { // 클래스 필드 name = 'Lee'; constructor() { console.log(name); // ReferenceError: name is not defined } } new Person();
3) 클래스 필드에 초기값을 할당하지 않으면 undefined를 갖는다.
class Person { // 클래스 필드를 초기화하지 않으면 undefined를 갖는다. name; } const me = new Person(); console.log(me); // Person {name: undefined}
4) 외부의 초기값으로 클래스 필드를 초기화해야 할 필요가 있다면 constructor에서 클래스 필드를 초기화해야 한다.
class Person { name; constructor(name) { // 클래스 필드 초기화. this.name = name; } } const me = new Person('Lee'); console.log(me); // Person {name: "Lee"}
따라서 외부 값에 따라 클래스 필드를 초기화 할 필요가 있다면 클래스 필드에 정의할 필요 없이 constructor에만 정의하면 된다. 이때, this 즉, 클래스가 생성한 인스턴스에 클래스 필드에 해당하는 프로퍼티가 없다면 클래스 필드에 자동으로 추가한다.
class Person { // name; constructor(name) { this.name = name; } } const me = new Person('Lee'); console.log(me); // Person {name: "Lee"}
5) 클래스 필드를 통해 메서드를 정의할 수 있다.
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
클래스 필드에 함수를 할당하는 경우, 이 함수는 프로토타입 메서드가 아닌 인스턴스의 메서드가 된다. 모든 클래스 필드는 인스턴스 프로퍼티가 되기 때문이다. 따라서 클래스 필드에 함수를 할당하는 것은 권장하지 않는다.
4. private 필드 정의 제안(Chrome 72이상, Node.js 버전 12이상)
자바스크립트 클래스의 인스턴스 프로퍼티는 언제나 외부에서 참조할 수 있다. 즉, public하다.
class Person { constructor(name) { this.name = name; // 인스턴스 프로퍼티는 기본적으로 public하다. } } // 인스턴스 생성 const me = new Person('Lee'); console.log(me.name); // Lee
클래스 필드 정의 제안을 사용하더라도 클래스 필드는 기본적으로 public 하기때문에 마찬가지로 외부에 그대로 노출된다.
class Person { name = 'Lee'; // 클래스 필드도 기본적으로 public하다. } // 인스턴스 생성 const me = new Person(); console.log(me.name); // Lee
Chrome 72이상, Node.js 버전 12이상에서는 외부에 해당 프로퍼티를 숨길 수 있는 private 필드가 지원된다. private 필드는 아래와 같은 특성을 가진다.
1) 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
2) private 필드는 클래스 내부에서만 참조할 수 있다.
클래스 외부에서 private 필드에 직접 접근할 수 있는 방법은 없다. 다만 접근자 프로퍼티를 통해 간접적으로 접근하는 방법은 유효하다.
class Person { // private 필드 정의 #name = ''; constructor(name) { this.#name = name; } // name은 접근자 프로퍼티다. get name() { // private 필드를 참조하여 trim한 다음 반환한다. return this.#name.trim(); } } const me = new Person(' Lee '); console.log(me.name); // Lee
3) private 필드는 반드시 클래스 몸체에 정의해야 한다.
private 필드를 직접 constructor에 정의하면 에러가 난다.
class Person { constructor(name) { // private 필드는 클래스 몸체에서 정의해야 한다. this.#name = name; // SyntaxError: Private field '#name' must be declared in an enclosing class } }
5. static 필드 정의 제안(Chrome 72이상, Node.js 버전 12이상)
클래스에는 static 키워드를 사용하여 정적 메서드를 정의할 수는 있었으나, 정적 필드를 정의할 수는 없었다. Chrome 72이상, Node.js 버전 12이상에서는 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
상속에 의한 클래스 확장
1. 클래스 상속과 생성자 함수 상속
생성자 함수의 프로토타입 기반 상속은 프로토타입 체인을 통해 다른 객체의 자산을 상속받는 개념이지만, 상속에 의한 클래스 확장은 기존 클래스를 상속받아 새로운 클래스를 확장하여 정의하는 것이다. 클래스는 상속을 통해 다른 클래스를 확장할 수 있는 문법인 extends 키워드가 기본적으로 제공된다. 생성자 함수는 그렇지 않다.
클래스의 확장 사용 왜 하는 걸까?
위 그림처럼 공통적으로 가지고 있는 특성을 수퍼 클래스로 묶고 차이가 나는 고유의 속성을 서브 클래스로 정의하여 공통적인 속성은 상속을 받아 사용할 수 있다.
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
2. extends 키워드
// 수퍼(베이스/부모)클래스 class Base {} // 서브(파생/자식)클래스 class Derived extends Base {}
상속을 통해 확장된 클래스를 서브클래스라고 하고, 서브클래스에 상속된 클래스를 수퍼클래스라고 한다.
extends 키워드의 역할은 수퍼클래스와 서브클래스 간의 상속 관계를 설정하는 것이다. 클래스도 프로토타입을 통해 상속 관계를 구현한다. 수퍼클래스와 서브클래스는 인스턴스의 프로토타입 체임뿐 아니라 클래스 간의 프로토타입 체인도 생성한다. 이를 통해 프로토타입 메서드, 정적 메서드 모두 상속이 가능하다.
3. 동적 상속
1) extends 키워드는 클래스뿐만 아니라 생성자 함수를 상속받아 클래스를 확장할 수도 있다.
extends 키워드 다음에는 클래스뿐만이 아니라 [[Construct]] 내부 메서드를 갖는 함수 객체로 평가될 수 있는 모든 표현식을 사용할 수 있다. 단 extends 앞에는 반드시 클래스다 와야 한다.
// 생성자 함수 function Base(a) { this.a = a; } // 생성자 함수를 상속받는 서브클래스 class Derived extends Base {} const derived = new Derived(1); console.log(derived); // Derived {a: 1}
2) 동적으로 상속받을 대상을 결정할 수 있다.
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
4. 서브클래스의 constructor
보통의 클래스에서 constructor를 생략하면 클래스에 다음과 같이 비어 있는 constructor가 암묵적으로 정의된다.
constructor() {}
서브 클래스에서 constructor를 생략하면 클래스에 다음과 같은 constructor가 암묵적으로 정의된다.
constructor(...args) { super(...args); }
args는 new 연산자와 함께 클래스를 호출할 때 전달한 인수의 리스트다.
super()는 수퍼클래스의 constructor를 호출하여 인스턴스를 생성한다.
// 수퍼클래스 class Base {} // 서브클래스 class Derived extends Base {} //⬇️⬇️⬇️ // 수퍼클래스 class Base { constructor() {} } // 서브클래스 class Derived extends Base { constructor() { super(); } } const derived = new Derived(); console.log(derived); // Derived {}
위 예제처럼 수퍼클래스와 서브클래스 모두 constructor를 생략하면 빈 객체가 생성된다. 인스턴스에 프로퍼티를 하려면 constructor 내부에서 인스턴스에 프로퍼티를 추가해야 한다.
5. super 키워드
super 키워드는 함수처럼 호출할 수도 있고 this와 같이 식별자처럼 참조할 수 있는 특수 키워드다.
- super를 호출하면 수퍼클래스의 constructor를 호출한다.
- super를 참조하면 수퍼클래스의 메서드를 호출할 수 있다.
1) super 호출 : super를 호출하면 수퍼클래스의 constructor를 호출한다.
수퍼 클래스의 constructor 내부에서 추가한 프로퍼티를 그대로 갖는 인스턴스를 생성한다면 서브클래스의 constructor를 생략할 수 있다. 이때, new 연산자와 함께 서브클래스를 호출하면 전달한 인수는 모두 수퍼클래스의 constructor에 전달된다.
// 수퍼클래스 class Base { constructor(a, b) { this.a = a; this.b = b; } } // 서브클래스 class Derived extends Base { // 다음과 같이 암묵적으로 constructor가 정의된다. // constructor(...args) { super(...args); } } const derived = new Derived(1, 2); console.log(derived); // Derived {a: 1, b: 2}
수퍼클래스에서 추가한 프로퍼티와 서브클래스에서 추가한 프로퍼티를 모두 갖는 인스턴스를 생성한다면 서브클래스의 constructor를 생략할 수 없다. new 연산자와 함께 서브클래스를 호출하면서 전달한 인수 중에서 수퍼클래스에 전달할 필요가 있는 인수는 서브클래스의 constructor에서 호출하는 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를 호출해야 한다.
class Base {} class Derived extends Base { constructor() { // ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor console.log('constructor call'); } } const derived = new Derived();
② 서브클래스의 constructor에서 super를 호출하기 전에는 this를 참조할 수 없다.
class Base {} class Derived extends Base { constructor() { // ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor this.a = 1; super(); } } const derived = new Derived(1);
③ super는 반드시 서브클래스의 constructor 안에서만 호출한다.
class Base { constructor() { super(); // SyntaxError: 'super' keyword unexpected here } } function Foo() { super(); // SyntaxError: 'super' keyword unexpected here }
2) super 참조 : 메서드 내에서 super를 참조하면 수퍼클래스의 메서드를 호출할 수 있다.
① 서브클래스의 프로토타입 메서드 내에서 super.sayHi는 수퍼클래스의 프로토타입 메서드 sayHi를 가리킨다.
// 수퍼클래스 class Base { constructor(name) { this.name = name; } sayHi() { return `Hi! ${this.name}`; } } // 서브클래스 class Derived extends Base { sayHi() { // super.sayHi는 수퍼클래스의 프로토타입 메서드를 가리킨다. return `${super.sayHi()}. how are you doing?`; } } const derived = new Derived('Lee'); console.log(derived.sayHi()); // Hi! Lee. how are you doing?
② 서브클래스의 정적 메서드 내에서 super.sayHi는 수퍼클래스의 정적 메서드 sayHi를 가리킨다.
// 수퍼클래스 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?
6. 상속 클래스의 인스턴스 생성 과정
// 수퍼클래스 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
위 예제 코드의 인스턴스 생성과정을 자세히 살펴보자. 위 예제의 프로토타입 체인은 다음과 같다.
1) 서브클래스의 super 호출
자바스크립트 엔진은 클래스를 평가할 때 수퍼클래스와 서브클래스를 구분하기 위해 "base" 또는 "derived"를 값으로 갖는 내부 슬롯 [[ConstructorKind]]를 갖는다. 생성자 함수와 다른 클래스를 상속받지 않는 클래스는 "base", 다른 클래스를 상속받는 클래스는 "derived" 값이 설정된다. 이를 통해 수퍼클래수와 서브클래스를 구분한다.
수퍼클래스는 앞서 클래스의 인스턴스 생성 과정과 동일하게 동작한다. 서브클래스는 자신이 직접 인스턴스를 생성하지 않고 수퍼클래스에게 인스턴스 생성을 위임한다. 따라서 서브클래스의 constructor에서 반드시 super를 호출해야하는 이유다.
2) 수퍼클래스의 인스턴스 생성과 this 바인딩
수퍼클래스의 constructor 내부의 코드가 실행되기 이전에 암묵적으로 빈 객체를 생성한다. 이 객체가 클래스가 생성한 인스턴스다. 이 인스턴스는 this에 바인딩된다. 그렇게 수퍼클래스의 constructor 내부의 this는 생성된 this를 가리킨다.
// 수퍼클래스 class Rectangle { constructor(width, height) { // 암묵적으로 빈 객체, 즉 인스턴스가 생성되고 this에 바인딩된다. console.log(this); // ColorRectangle {} // new 연산자와 함께 호출된 함수, 즉 new.target은 ColorRectangle이다. console.log(new.target); // ColorRectangle ...
인스턴스는 수퍼클래스가 생성한 것이다. 하지만 new 연산자와 함께 호출된 클래스가 서브클래스인 것인 중요하다. 즉, 인스턴스는 new.target이 가리키는 서브클래스가 생성한 것으로 처리된다. 따라서 생성된 인스턴스의 프로토타입은 서브클래스의 prototype 프로퍼티가 가리키는 객체다.
// 수퍼클래스 class Rectangle { constructor(width, height) { console.log(this); // ColorRectangle {} // 생성된 인스턴스의 프로토타입으로 ColorRectangle.prototype이 설정된다. console.log(Object.getPrototypeOf(this) === ColorRectangle.prototype); // true console.log(this instanceof ColorRectangle); // true console.log(this instanceof Rectangle); // true ... const colorRectangle = new ColorRectangle(2, 4, 'red'); console.log(colorRectangle); // ColorRectangle {width: 2, height: 4, color: "red"}
3) 수퍼클래스의 인스턴스 초기화
수퍼클래스의 constructor가 실행되어 this에 바인딩되어 있는 인스터스를 초기화한다. 즉 인스턴스에 프로퍼티를 추가하고 constructor가 인수로 전달받은 초기값으로 인스턴스의 프로퍼티를 초기화한다.
// 수퍼클래스 class Rectangle { constructor(width, height) { // 암묵적으로 빈 객체, 즉 인스턴스가 생성되고 this에 바인딩된다. console.log(this); // ColorRectangle {} // 인스턴스 초기화 this.width = width; this.height = height; console.log(this); // ColorRectangle {width: 2, height: 4} } ...
4) 서브클래스 constructor로의 복귀와 this 바인딩
super 호출이 종료되고 제어 흐름이 서브클래스 constructor로 돌아온다. 이때 super가 반환한 인스턴스가 this에 바인딩된다. 서브클래스는 별도의 인스턴스를 생성하지 않고 super가 반환한 인스턴스를 thisdp 바인딩하여 그대로 사용한다.
// 서브클래스 class ColorRectangle extends Rectangle { constructor(width, height, color) { super(width, height); // super가 반환한 인스턴스가 this에 바인딩된다. console.log(this); // ColorRectangle {width: 2, height: 4} ...
super가 호출되지 않으면 인스턴스가 생성되지 않으며, this도 바인딩 할 수 없다. 이것이 서브클래스의 constructor에서 super를 호출하기 전에는 this를 참조할 수 없는 이유다.
5) 서브클래스의 인스턴스 초기화
super 호출 이후, 서브클래스의 constructor에 기술되어 있는 인스턴스 초기화가 실행된다. 즉 인스턴스에 서브클래스에 정의되어 있는 프로퍼티를 추가하고 constructor 인수로 전달받은 초기값으로 인스턴스 프로퍼티를 초기화한다.
6) 인스턴스 반환
클래스의 모든 처리가 끝나면 완성된 인스턴스가 바인딩된 this가 암묵적으로 반환된다.
// 서브클래스 class ColorRectangle extends Rectangle { constructor(width, height, color) { super(width, height); // super가 반환한 인스턴스가 this에 바인딩된다. console.log(this); // ColorRectangle {width: 2, height: 4} // 인스턴스 초기화 this.color = color; // 완성된 인스턴스가 바인딩된 this가 암묵적으로 반환된다. console.log(this); // ColorRectangle {width: 2, height: 4, color: "red"} } ...
7. 표준 빌트인 생성자 함수 확장
String, Number, Array 같은 표준 빌트인 객체도 [[Construct]] 내부 메서드를 갖는 생성자 함수이므로 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
위 예제에서 Array.prototype의 메서드 중에서 새로운 배열을 반환하는 filter, reduce와 같은 메서드가 MyArray클래스의 인스턴스를 반환한다. myArray.filter가 반환하는 인스턴스는 MyArray 클래스가 생성한 인스턴스 즉, MyArray타입이므로 myArray.filter가 반환하는 인스턴스로 uniq 메서드를 연이어 호출할 수 있다.(메서드 체이닝)
'사부작사부작 > Javascript' 카테고리의 다른 글
[Javascript]배열(2) 메서드 (0) 2022.04.13 [Javascript]배열(1)정의, 특징, 생성 방법 (0) 2022.04.12 [Javascript]Class (1)정의와 메서드 (0) 2022.03.29 [Javascript] 클로져 (0) 2022.03.29 [Javascript]실행컨텍스트 (0) 2022.03.27