웹(web)/프론트엔드-javascript

생성자 함수와 상속

바코94 2020. 6. 27. 18:40

개, 고양이처럼 type, name, sound (종류, 이름, 짖는 소리)에 따라 만들고 싶다면?

function Animal(type, name, sound) {

  this.type = type;

  this.name = name;

  this.sound = sound;

  this.say = function() {

  console.log(this.sound);

  };

};

const dog1 = new Animal("개", "멍멍이", "멍멍");

dog1.say();

const dog2 = new Animal("개", "시바견", "머엉머엉");

dog2.say();

 

 

공통으로 사용되는 say를 일반화 하고 싶다면?

function Animal(type, name, sound) {

  this.type = type;

  this.name = name;

  this.sound = sound;

}

Animal.prototype.say = function() {

  console.log(this.sound);

};

 

 

Dog 클래스를 만들려면?

function Dog(name, sound) {

  Animal.call(this, "개", name, sound);

}

Dog.prototype = Animal.prototype;