갈푸라떼
갈푸라떼는 개발중
갈푸라떼
전체 방문자
오늘
어제
  • 분류 전체보기 (232)
    • CS (0)
      • CSinfo (0)
    • Frontend (15)
      • HTML,CSS (1)
      • Javascript (2)
      • React (0)
      • React Hook (12)
    • Backend (0)
      • Python (0)
      • Node.js (0)
      • php (0)
    • DB (2)
      • MySQL (2)
      • BigQuery (0)
      • Mongodb (0)
    • Study (186)
      • JavaScript (72)
      • JavaScript(Clean code) (50)
      • Node.js (11)
      • HTML,CSS (13)
      • React (30)
      • TypeScript (10)
      • React-Native (0)
    • Error (2)
      • error (2)
    • Git (22)
      • Git (22)
    • Help Coding (4)
      • Useful websites (3)

블로그 메뉴

  • 홈
  • 태그
  • 방명록
  • Github

공지사항

인기 글

태그

  • 호이스팅
  • Arrow
  • 함수
  • this
  • structure
  • ECMAScript
  • 이터러블
  • nodemon
  • 실행 컨텍스트
  • PM2
  • 오버라이딩
  • 원시타입
  • class
  • 컴파일러
  • SPREAD
  • 자바스크립트엔진
  • symbol
  • 인터프리터
  • 스코프 체인
  • 싱글스레드
  • 렉시컬 환경
  • 프로토타입
  • 정적 레벨
  • 상속
  • 심볼
  • Babel
  • prototype
  • 네이밍
  • function
  • 객체타입

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
갈푸라떼

갈푸라떼는 개발중

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);

'Study > JavaScript' 카테고리의 다른 글

[JavaScript_study] 클로저(Closure)  (0) 2022.04.14
[JavaScript_study] Mixin  (0) 2022.04.14
[JavaScript_study] freeze (불변성을 추구할 때)  (0) 2022.04.14
[JavaScript_study] 프로퍼티(property)  (0) 2022.04.14
[JavaScript_study] 프로토타입(Prototype)  (0) 2022.04.14
    'Study/JavaScript' 카테고리의 다른 글
    • [JavaScript_study] 클로저(Closure)
    • [JavaScript_study] Mixin
    • [JavaScript_study] freeze (불변성을 추구할 때)
    • [JavaScript_study] 프로퍼티(property)
    갈푸라떼
    갈푸라떼

    티스토리툴바