모던 자바스크립트 Deep Dive 25장 정리 - 클래스 2

Hyodduru ·2022년 8월 1일
1
post-thumbnail

25.7 프로퍼티

🧐 인스턴스 프로퍼티

✔️ 인스턴스 프로퍼티는 constructor 내부에서 정의해야 한다.
✔️ 언제나 public하다. why? ES6클래스는 다른 객체지향 언어처럼 private, public, protected 키워드와 같은 접근 제한자(access modifier)를 지원하지 않음.

ex)

class Person{
  constructor(name){
    // 인스턴스 프로퍼티
    this.name = name;
  }
}

🧐 접근자 프로퍼티

접근자 프로퍼티(access property)는 자체적으로는 값을 갖지 않고 다른 데이터 프로퍼티의 값([[value]])을 읽거나 저장할 때 사용하는 접근자 함수(accessor function)로 구성된 프로퍼티.
👉 getter 함수와 setter 함수로 구성되어 있음.

ex)

const person = {
  //데이터 프로퍼티
  firstName : 'Hyojeong',
  lastName : 'Kim',
 
  //fullName은 접근자 함수로 구성된 접근자 프로퍼티이다.
  //getter 함수
  get fullName(){
    return `${this.firstName} ${this.lastName}`
    
  //setter 함수 
    set fullName(){
      [this.firstName, this.lasName] = name.split(' ');
    }
  };
  
  //데이터 프로퍼티를 통한 프로퍼티 값의 참조 
  console.log(`${person.firstName} ${person.lastName}`); // Hyojeong kim

// 접근자 프로퍼티를 통한 프로퍼티 값의 저장
// 접근자 프로퍼티 fullName에 값을 저장하면 setter 함수가 호출된다.
person.fullName = 'Heegun Lee';
console.log(person); // {firstName : 'Heegun', lastName : 'Lee'}

// 접근자 프로퍼티를 통한 프로퍼티 값의 참조 
// 접근자 프로퍼티 fullName에 접근하면 getter 함수가 호출된다. 
console.log(person.fullName);// Heegun Lee 
  
console.log(Object.getOwnPropertyDescriptor(person, 'fullName'));
// {get :f, set:f, enumberable : true, configurable : true}
 

✔️ 접근자 프로퍼티는 get, set, enumberable, configurable 프로퍼티 어트리뷰트를 갖는다.

✔️ 접근자 프로퍼티는 클래스에서도 사용 가능.
ex)

class Person {
  constructor(firstName, lastName){
    this.firstName = firstName;
    this.lastName = lastName;
  }
  
  get fullName()
  {
    return `${this.firstName} ${this.lasName}`;
  }
  
  set fullName(name){
    [this.firstName, this.lastName] = name.split(' ');
  }
}

const me = new Person('Hyojeong', 'Kim');

// 접근자 프로퍼티인 fullName의 값 저장 => setter 함수 호출 
me.fullName = 'Heegun Lee';

// fullName에 접근 => getter 함수 호출
console.log(me.fullName);  // 'Heegun Lee'

console.log(Object.getOwnPropertyDescriptor(Person.prototype, 'fullName'));
// {get :f, set:f, enumberable : true, configurable : true}

                   

✔️ getter와 setter는 직접 호출하지 않음! 즉 인스턴스의 프로퍼티처럼 사용이 된다. 👉 getter는 프로퍼티처럼 참조하는 형식으로 사용, setter는 프로퍼티처럼 값을 할당하는 형식으로 사용. 할당 시 내부적으로 setter가 호출되는 것!

✔️ getter는 무언가를 취득할 때 사용하므로 반드시 무언가를 반환해야함. (return 필수)

✔️ setter는 무언가를 프로퍼티에 할당해야 할 때 사용하므로 반드시 매개변수 있어야 함. 단 하나의 값만 할당받기 때문에 단 하나의 매개변수만 선언할 수 있음!

✔️ 접근자 프로퍼티는 인스턴스의 프로퍼티가 아닌 프로토타입의 프로퍼티가 된다. 👉 클래스의 메서드는 기본적으로 프로토타입 메서드가 되기 때문.

ex)

Object.getOwnPropertyNames(me); // ["firstName", "lastName"]
Object.getOwnPropertyNames(Object.getPrototypeOf(me)); // ["constructor", "fullName"] 

🧐 클래스 필드 정의 제안

클래스 필드?

클래스 기반 객체지향 언어에서 클래스가 생성할 인스턴스의 프로퍼티.

🔖 참고)
클래스 기반 객체지향 언어인 자바의 클래스 필드 => 클래스 내부에서 변수처럼 사용된다. 자바스크립트 클래스 몸체에는 메서드만 선언할수 있기에, 자바와 유사하게 클래스 필드 선언할 경우 문법 에러 발생. But, 자바스크립트에서도 인스턴스 프로퍼티를 마치 클래스 기반 객체지향 언어의 클래스 필드처럼 정의할 수 있는 새로운 표준 사양인 "Class field declarations" 가 2021년 1월 TC39 프로세스의 state3에 제안되어 있음.

🔖 TC39(Technical Committee)? ECMAScript 관리를 담당하는 위원회

ex) java의 class field - 클래스 필드 몸체에 this 없이 선언해야 함.

public class Person{
	private String firstName = "";
    
    // 생성자 
    Person(String firstName){
    // this는 언제나 클래스가 생성할 인스턴스 가리킴. 
    this.firstName = firstName;
    }
    
    public String getFullName(){
    // this 없이도 클래스 필드를 참조할 수 있음.
    return firstName;
    }
 }

ex) 최신 브라우저(Chrome 72이상), 최신 Node.js(버전 12 이상) 자바스크립트 - 클래스 필드를 클래스 몸체에 정의할 수 있음.

class Person{
  // 클래스 필드 정의 
  name = 'Lee'
}

const me = new Person();
console.log(me); // Person {name : "Lee"}

✔️ 클래스 몸체에서 클래스 필드를 정의하는 경우 this에 클래스 필드 바인딩해서는 안된다. this는 클래스의 constructor와 메서드 내에서만 유효.

ex)

class Person{
  this.name = ''; // SyntaxError
}

✔️ 자바와 다르게 자바스크립트에서는 클래스 필드 참조할 경우 this 반드시 사용해야함.

class Person {
  name = 'Lee';

consructor(){
  console.log(name); // Reference Error : name is not defined
}
}

✔️ 클래스 필드에 초기값 할당하지 않으면 undefined를 가짐.

✔️ 인스턴스를 생성할 때 외부의 초기값으로 클래스 필드를 초기화해야할 필요가 있다면 constructor 내에서 해줄 것

class Person{
  name;
  
  constructor(name){
    // 클래스 필드 초기화 
    this.name = name;
  }
}

const me = new Person('Lee');
console.log(me); // Person {name : 'Lee'}

하지만 이런 경우 굳이 name을 클래스필드에 정의할 필요 없음!

✔️ 클래스 필드를 통해 메서드를 정의할 수도 있음.

class Person {
  name = 'Lee';

getName = function(){
  return this.name;
 }
}

console.log(me.getName()); // Lee 

🚨 클래스 필드에 함수 할당하는 경우, 프로토타입 메서드가 아닌 인스턴스 메서드가 되기 때문에, 클래스 필드에 함수를 할당하는 것은 바람직하지 않음!

🧐 private 필드 정의

✔️ TC39 프로세스의 stage3에서는 private 필드 정의할 수 있는 새로운 표준 사양이 제안되어있음. => #를 붙혀주는 방식
ex)

class Person {
  // private 필드 정의 
  #name = '';
  
  constructor(name){
    this.name = name;
  }

get name(){
  	return this.#name.trim();
 }
}

const me = new Person('Lee');

console.log(me.#name); // Syntax Error : Private field '#name' must be declared in an enclosing class 
            
console.log(me.name); // Lee 

✔️ private 필드는 접근자 프로퍼티를 통해 간접적으로 접근할 수 있음.

🔖 참고)
자바스크립트의 상위 확장(superset)인 타입스크립트는 클래스 기반 객체지향 언어가 지원하는 접근 제한자인 public, private, protected를 모두 지원함.

🧐 static 필드 정의 제안

static public 필드, static private 필드, static private 메서드를 정의할 수 있는 새로운 표준 사양인 "Static class features" 현재 TC39 프로세스의 stage3에 제안되어 있음.

이 제안중, static public/private 필드는 최신 브라우저 (Chrome 72이상), 최신 Node.js(버전 12 이상)에 이미 구현되어 있음.

ex)

class MyMath{
  // static public 필드 정의
  static PI = 22 / 7;

// static private 필드 정의
static #num = 10;

// static 메서드 
static increment(){
  return ++MyMath.#num;
 }
}

console.log(MyMath.PI); // 3.14~~~ 
console.log(MyMath.increment()); // 11 

25.8 상속에 의한 클래스 확장

🧐 클래스 상속?

상속에 의한 클래스 확장은 기존 클래스를 상속받아 새로운 클래스를 확장(extends)하여 정의하는 것 👉 프로토타입 기반 상속은 프로토타입 체인을 통해 다른 객체의 자산을 상속받는 개념이라는 점에서 차이가 있음.

🧐 클래스 상속과 생성자 함수 상속의 비교

이 둘은 인스턴스를 생성할 수 있는 함수라는 점에서 유사. 하지만 클래스는 상속을 통해 기존 클래스를 확장할 수 있는 문법 기본적으로 제공되지만 생성자 함수는 그렇지 않음.
👉 class는 상속을 통해 다른 클래스를 확장할 수 있는 문법인 extends 키워드가 기본적으로 제공됨.

자바스크립트는 클래스 기반 언어가 아니므로, 생성자 함수를 사용하여 클래스를 흉내 내려는 시도는 권장하지 않음!

🧐 extends 키워드

extends 키워드는 수퍼클래스와 서브클래스 간의 상속 관계를 설정함.
클래스도 프로토타입을 통해 상속 관계를 구현.

// 수퍼 클래스
class Base{}

// 서브 클래스 
class Derived extends Base{}

🧐 동적 상속

✔️ extends는 클래스 뿐만 아니라 생성자 함수를 상속받아 클래스를 확장할 수도 있음. 단 extends 키워드 앞에는 반드시 class가 와야함.

// 생성자 함수
function Base(a){
  this.a = a;
}

// 생성자 함수를 상속받는 서브클래스
class Derived extends Base{}

cosnt derived = new Derived(1);
console.log(derived); // Derived { a : 1 };

✔️ extends 키워드 다음에는 클래스뿐만이 아니라 [[Constructor]]내부 메서드를 갖는 함수 객체로 평가될 수 있는 모든 표현식 사용 가능

let condition = true;

// 조건에 따라 동적으로 상속 대상을 결정하는 서브 클래스 
class Derived extends (condition? Base1 : Base2){}

🧐 서브클래스의 constructor

✔️ 클래스에서 constructor 생략시 비어있는 constructor가 암묵적으로 정의되기된다. 서브클래스에서는, args와 super가 함께 정의된다.

constructor(...args) {super(...args)}

👉 args는 new 연산자와 함께 클래스를 호출할 때 전달한 인수의 리스트
👉 super()는 수버클래스의 constructor를 호출하여 인스턴스를 생성함.

🧐 super 키워드

✔️ super 를 호출하면, 수퍼클래스의 constructor(super-constructor)를 호출함.
✔️ super를 참조하면 수퍼클래스의 메서드를 호출할 수 있음.

ex)

// 수퍼클래스
class Base{
  constructor(a,b){
    this.a = a;
    this.b = b;
  }
}

// 서브클래스 
class Derived extends Base {
}

const derived = new Derived(1,2);
console.log(derived); // Derived {a:1,b:2}

만약 derived 생성할 때 새로운 인수를 전달해야한다면, 서브클래스 constructor 생략 불가능!

ex)

class Derived extends Base {
constructor(a,b,c){
super(a,b);
this.c = c;
  }
 }
}

const derived = new Derived(1,2,3);

🚨 super 호출 시 주의사항

✔️ 서브클래스에서 constructor를 생략하지 않는 경우 서브클래스의 constructor에서는 반드시 super를 호출해야함!
✔️ 서브클래스의 constructor에서 super를 호출하기 전에는 this를 참조할 수 없음!
✔️ super는 반드시 서브클래스의 constructor에서만 호출함! 서브클래스가 아닌 클래스의 constructor나 함수에서 super를 호출하면 에러가 발생.

super 참조

✔️ 서브클래스의 프로토타입 메서드 내에서 super.sayHi는 수퍼클래스의 프로토타입 메서드를 가리킨다.

✔️ 서브클래스의 정적 메서드 내에서 super.sayHi는 수퍼클래스의 정적 메서드 sayHi를 가리킨다.

🧐 상속 클래스의 인스턴스 생성 과정

  1. 서브클래스의 super 호출
    서브클래스는 자신이 직접 인스턴스를 생성하지 않고 수퍼클래스에게 인스턴스 생성을 위임한다. 이것이 바로 서브클래스의 constructor에서 반드시 super를 호출해야하는 이유!
  2. 수퍼클래스의 인스턴스 생성과 this 바인딩
    수퍼클래스의 constructor 내부의 코드가 실행되기 전에 암묵적으로 빈 객체를 생성함 👉 빈 객체 === 클래스가 생성한 인스턴스 👉 해당 객체는 this에 바인디잉 된다. 즉 수퍼클래스의 constructor 내부의 this는 생성된 인스턴스를 가리킴

🚨주의) 인스턴스는 수퍼클래스가 생성한 것. 하지만 new 연산자와 함께 호출된 클래스는 서브클래스. 즉 인스턴스는 new.target이 가리키는 서브클래스가 생성한 것으로 처리된다! 👉 생성된 인스턴스의 프로토타입은 서브클래스의 prototype 프로퍼티가 가리키는 객체임! (ColorRectangle.prototype)

// 수퍼 클래스 
class Regtangle{
  constructor(width, height){
    console.log(this); // 빈 객체 => ColorRectangle{} 생성된 인스턴스 
    console.log(new.target); // ColorRectangle
  1. 수퍼클래스의 인스턴스 초기화
    수퍼클래스의 constructor가 실행되어 this에 바인딩되어있는 인스턴스 초기화
  2. 서브클래스 constructor로의 복귀와 this 바인딩
    super의 호출 종료되고 제어 흐름이 서브 클래스의 constructor로 돌아옴.
    이때 super가 반환한 인스턴드가 this에 바인딩된다. 서브클래스는 별도의 인스턴스 생성하지 않고 super가 반환한 인스턴스를 this에 바인딩하여 그대로 사용함.
// 서브클래스 
class ColorRectangle extends Rectangle {
constructor (width, height, color) {
	super(width, height);
    
    
    // super가 반환한 인스턴스가 this에 의해 바인딩 된다. 
    console.log(this); // ColrRectangle {width : 2, height : 4}
    }

이처럼 super가 호출되지 않으면 인스턴스 생성되지 않음, this의 바인딩 또한 불가능. 서브클래스의 constructor에서 super를 호출하기 전에는 this를 참조할 수 없는 이유가 바로 이때문!
5. 서브클래스의 인스턴스 초기화
6. 인스턴스 반환
클래스의 모든 처리 끝나면 완성된 인스턴스가 바인딩된 this 암묵적으로 반환함.

🧐 표준 빌트인 생성자 함수 확장

✔️ String, Number, Array 같은 표준 빌트인 객체도 [[Constructor]]내부 메서드를 갖는 생성자 함수이므로 extends 키워드를 사용하여 확장할 수 있음

ex)

class MyArray extends Array{
  uniq(){
    return this.filter((v,i,self) => self.indexOf(v) === i);}
}

const myArray = new MyArray(1,1,2,3);

console.log(myArray.uniq());// MyArray(3) [1,2,3]
    

✔️ MyArray 클래스는 Array.prototype과 MyArray.prototype의 모든 메서드를 사용할 수 있음. 주의할 것은, map,filter와 같이 새로운 배열을 반환하는 메서드는 MyArray 클래스의 인스턴스를 반환함! => 메서드 체이닝 가능

console.log(myArray.filter(v => v % 2).uniq()); // [1,3]

✔️ 만약 MyArray 클래스의 uniq 메서드가 MyArray 클래스가 생성한 인스턴스가 아닌 Array가 생성한 인스턴스를 반환하게 하려면 Symbol.species를 사용하여 정적 접근자 프로퍼티를 추가함

class MyArray extends Array{
  // 모든 메서드가 Array타입의 인스턴스를 반환하도록 함.
  static get [Symbol.species]() {return Array;}
  
  // 이하 생략
  
}
profile
꾸준히 성장하기🦋 https://hyodduru.tistory.com/ 로 블로그 옮겼습니다

0개의 댓글