CodeStates/JavaScript

Section2 / Unit2 : JS 객체 지향 프로그래밍 복습

yeeendy 2023. 5. 12. 11:44
class Human{
    constructor(name, age){
        this.name = name;
        this.age = age;
    }
}

class Student extends Human{
    constructor(name, age, grade){
        super(name, age);
        this.grade = grade;
    }
}
const me = new Student('나', 20, 100);

me.name;  // '나'
me.age;  // 20
me.grade;  // 100
me.__proto__ === Student.prototype  // true
me.__proto__ === Human.prototype  //false
me.__proto__.__proto__ === Human.prototype  // true
me.__proto__.__proto__.__proto__ === Object.prototype  // true
me.__proto__.__proto__.__proto__.__proto__ === null  // true

 

super

  • 부모 오브젝트의 함수를 호출할 때 사용
  • super.prop과 super[expr] 표현식은 클래스와 객체리터럴의 어떠한 메서드 정의 방법에도 유효
super([arguments]);  // 부모 생성자 호출
super.functionOnParent([arguments]);
  • 생성자에서는 super 키워드 하나만 사용
  • this 키워드가 사용되기 전에 호출
  • 부모 객체의 함수를 호출하는 데 사용
class Polygon {
  constructor(height, width) {
    this.name = 'Polygon';
    this.height = height;
    this.width = width;
  }
  sayName() {
    console.log('Hi, I am a ', this.name + '.');
  }
}

class Square extends Polygon {
  constructor(length) {
    this.height; // 참조오류가 발생합니다. super가 먼저 호출되어야 합니다.

    // 여기서, 부모클래스의 생성자함수를 호출하여 높이값을 넘겨줍니다.
    // Polygon의 길이와 높이를 넘겨줍니다.
    super(length, length);

    // 참고: 파생 클래스에서 super() 함수가 먼저 호출되어야
    // 'this' 키워드를 사용할 수 있습니다. 그렇지 않을 경우 참조오류가 발생합니다.
    this.name = 'Square';
  }

  get area() {
    return this.height * this.width;
  }

  set area(value) {
    this.area = value;
  }
}
// 정적 메서드에서의 super 호출
class Human {
  constructor() {}
  static ping() {
    return 'ping';
  }
}

class Computer extends Human {
  constructor() {}
  static pingpong() {
    return super.ping() + ' pong';
  }
}
Computer.pingpong(); // 'ping pong'
//super의 속성 삭제
//Delete 사용 X
//super.prop, super[expr] 표현식을 활용하여 삭제하면 레퍼런스 에러
class Base {
  constructor() {}
  foo() {}
}
class Derived {
  constructor() {}
  delete() {
    delete super.foo;
  }
}

new Derived().delete(); // 참조오류: 'super'완 관련된 삭제가 유효하지 않습니다.

 

extends

  • 클래스를 다른 클래스의 자식으로 만들기 위해 class 선언 또는 class 식에 사용
class DateFormatter extends Date {

  getFormattedDate() {
    const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
      'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    return `${this.getDate()}-${months[this.getMonth()]}-${this.getFullYear()}`;
  }

}

console.log(new DateFormatter('August 19, 1975 23:15:30').getFormattedDate());
// Expected output: "19-Aug-1975"