Study/JavaScript

[JavaScript_study] 상속(inheritance) // prototype, class

갈푸라떼 2022. 4. 14. 17:17

* 객체지향 프로그래밍의 가장 큰 특징 및 장점

  • 상속을 통한 코드의 재사용성

* 요즘 최신 자바스크립트, 타입스크립트, 다른 객체 지향언어에서는 prototype를 베이스로 하지않고 Class를 이용해서 조금 더 간편하게 한다.


* 브라우저, node환경에서는 최근 자바스크립트, 타입스크립트에서 제공하는 Class를 사용하기 때문에 prototype에 대해서 일일이 작성하지는 않는다.


* 상속 예시 코드

  • 프로토타입을 베이스로 한 객체지향 프로그래밍
// 프로토타입을 베이스로한 객체지향 프로그래밍
function Animal(name, emoji) {
  this.name = name;
  this.emoji = emoji;
}

Animal.prototype.printName = function () {
  console.log(`${this.name} ${this.emoji}`);
};

function Dog(name, emoji, owner) {
  // super(name, emoji)
  // Object.create()를 사용하여 prototype를 받게되면 super()처럼 생성자를 이용해 연결을 해주어야 한다.
  // call()이라는 static함수를 이용해서 super()와 동일한 기능을 사용할 수 있다.
  Animal.call(this, name, emoji);
  // Dog에만 필요한것을 아래와 같이 구성해준다.
  this.owner = owner;
}
// Dog.prototype = Object.create(Object.prototype); // 인자로 전달한 prototype을 베이스로 해서 새로운 object를 만들어준다.
Dog.prototype = Object.create(Animal.prototype); // 인자로 전달한 prototype을 베이스로 해서 새로운 object를 만들어준다.(Animal prototype를 베이스로 함)

Dog.prototype.play = () => {
  console.log('같이 놀자옹!');
};

function Tiger(name, emoji) {
  Animal.call(this, name, emoji);
}

Tiger.prototype = Object.create(Animal.prototype);
Tiger.prototype.hunt = () => {
  console.log('사냥하자! ..🐇..');
};

const dog1 = new Dog('멍멍', '🐶', '엘리');
dog1.play();
dog1.printName();
const tiger1 = new Tiger('어흥', '🐯');
tiger1.printName();
tiger1.hunt();

// 상속도 확인하는 법
console.log(dog1 instanceof Dog);
console.log(dog1 instanceof Animal);
console.log(dog1 instanceof Tiger);
console.log(tiger1 instanceof Dog);
console.log(tiger1 instanceof Animal);
console.log(tiger1 instanceof Tiger);

 

* 상속 예시 코드

  • 클래스를 베이스로 한 객체지향 프로그래밍
// 클래스를 베이스로한 객체지향프로그래밍
class Animal {
  constructor(name, emoji) {
    this.name = name;
    this.emoji = emoji;
  }
  printName() {
    console.log(`${this.name} ${this.emoji}`);
  }
}

// 이름과 이모지를 공통적으로 받으니까 생략이 가능하다.
class Dog extends Animal {
  play() {
    console.log('같이 놀자옹!');
  }
}

// 이름과 이모지를 공통적으로 받으니까 생략이 가능하다.
class Tiger extends Animal {
  hunt() {
    console.log(`사냥하자! ..🐇..`);
  }
}

const dog1 = new Dog('뭉치', '🐶');
const tiger1 = new Tiger('어흥', '🐯');
dog1.printName();
tiger1.printName();
dog1.play();
tiger1.hunt();

console.log(dog1 instanceof Dog);
console.log(dog1 instanceof Animal);
console.log(dog1 instanceof Tiger);
console.log(tiger1 instanceof Tiger);