코딩쌀롱

[JS] prototype ↔︎ class 본문

개발공부

[JS] prototype ↔︎ class

이브✱ 2021. 3. 10. 15:55

 

✱ class 예시 코드

// Car 부모 클래스
class Car {
   constructor(brand) {
     this.carname = brand;
   }
   
   present () {
     return `I have a ${this.carname}`
   }
}


// Car를 상속받는 Model 클래스
class Model extends Car{
   constructor(brand, mod) {
     super(brand)
     this.model = mod;
   }
   
   show () {
     return this.present() + `, It is a ${this.model}`
   }
}


const mycar = new Model('Ford', 'Mustang');
mycar.show()  //"I have a Ford, It is a Mustang"

 

✱ prototype 예시 코드

// 부모 Car
function Car(brand) {
   this.carname = brand;
}

Car.prototype.present = function() {
   return `I have a ${this.carname}`;
}


// 상속받는 Model 
function Model(brand, mod) {
  Car.call(this, brand)
  this.model = mod;
}

Model.prototype = Object.create(Car.prototype);
Model.prototype.show = function() {
  return this.present() + `, It is a ${this.model}`;
}


const mycar = new Model("Ford", "Mustang");
mycar.show()  //"I have a Ford, It is a Mustang"

 

상태(속성)을 상속받을 때는 super, call

// 클래스에서는
super(brand);

// 프로토타입에서는
Car.call(this, brand);

 

Car함수를 call로 실행시켜서 this를 상속받는 객체 Model로 바인딩해준다. 

인스턴스 생성 과정 중 속성 부분만 설명하자면 아래와 같다.

new Model() → Model 생성자 함수 호출 → Car.call(this, brand)this.carname = brand; → this.model = mod;

 

결과적으로, new Model()을 했을 때 아래와 같다고 할 수 있다.

this.carname = brand;
this.model = mod;

 

 

 프로토타입 객체를 상속받을 때는 extends, Object.create

// 클래스에서는
class Model extends Car {~}

// 프로토타입에서는
Model.prototype = Object.create(Car.prototype)

 

Comments