프로토타입, 상속

유주성·2023년 5월 12일
0
post-thumbnail

자바스크립트는 프로토타입 언어이다. 이 의미는 객체를 상속시키기위해 프로토타입이라는 방식을 이용해 상속시킨다는 것이다.

class Human {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  sleep() {
    console.log(`${this.name}은 잠에 들었습니다`);
  }
}

let coder = new Human('김코딩', 30);

Human.prototype.constructor === Human; 
Human.prototype === coder.__proto__; 
Human.prototype.sleep === coder.sleep;

prototype은 해당 클라스의 프로토타입에 들어갈 때 사용하는 것이고, __proto__ 는 클라스의 위치에서 프로토타입에 들어갈때 사용하는 것이다.

Human + .prototype -> Human.prototype
Human.prototype + new Human() -> coder

coder + .prototype -> Human.prototype
Human.prototype + .constructor -> Human

상속

클라스는 상속하여 사용이 가능하다. 상속은 super 과 extends를 이용해 한다. 상속된 자식 클라스는 부모의 속성과 매서드를 이용 가능하다. extends로 상속받을 부모 클라스를 선택하고, super로 상속받을 요소를 선택한다.

class Human {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  sleep() {
    console.log(`${this.name}은 잠에 들었습니다`);
  }
}

class student extends Human{
  consructor(name, age, grade){
    super(name, age);
    this.grade = grade;
  }
  study() {
    console.log(`${this.name}은 공부를 하였습니다.`);
    this.grade += 10
  }
}
  
let coder = new Human('김코딩', 30);
let writer = new student('유주성',25,90);

0개의 댓글