JS 객체지향 복습 4

2021. 7. 12. 16:57JS/객체지향

[반복하지 않도록 상속 사용]

프로그래밍에는 "Don't Repeat Yourself" (DRY)라는 원칙이 있습니다.  반복 코드는 일반적으로 작업량이 많아지고 오류의 여지가 많아진다는 것을 의미합니다.

Cat.prototype= {

 constructor: Cat,

 say: function(){

  console.log("Hello " + this.name);

 }

};

Dog.prototype= {

 constructor: Dog,

 say: function(){

  console.log("Hello " + this.name);

 }

};

say 메소드는 Cat과 Dog에서 반복이 됩니다. 이럴 땐 supertype을 만들어 해결할 수 있습니다.

Animal.prototype= {

 constructor:Animal,

 say: function(){

  console.log("Hello " + this.name);

 }

};

let Cat = Object.create(Animal.prototype);

let su = new Cat("su");

supertype Animal을 만들어 Cat과 Dog에 있는 say를 지울 수 있습니다. Animal의 prototype을 사용하기 위하여

Object.create()를 사용했습니다. 새로운 new object를 생성하고 object를 new object의 prototype으로 설정합니다.

su는 Animal 의 모든 속성을 상속합니다. 

 

[상속된 생성자 속성 재설정]

let Cat = Object.create(Animal.prototype);

let su = new Cat("su");

su가 Cat에 의해 만들어 졌다는 것을 보여주기 위해서는 Cat의 개체로 수동 설정해야 합니다. 

Cat.prototype.constructor = Cat;

 

[상속 후 메소드 추가]

Animal에 상속된 Cat에 고유한 동작을 추가하려고 하면 constructor 함수와 동일한 방식으로 Cat의 prototype에 추가됩니다. 

Cat.prototype.sleep = function(){ 

 console.log("Time for bed");

};

Cat constructor로 만들어진 su는 이제 Cat에 있는 sleep까지 포함해 모두 사용할 수 있습니다.

su.say();

su.sleep();

'JS > 객체지향' 카테고리의 다른 글

JS 객체지향 복습 5  (0) 2021.07.12
JS 객체지향 복습 3  (0) 2021.07.12
JS 객체지향 복습 1  (0) 2021.07.12