본문 바로가기
언어의 기초/자바스크립트(Javascript)

[Javascript]Object.create() & ES6

by 지에스정 2020. 5. 12.

 

프로토타입을 상속받는 방법에는 추가적인 방법이 더 있다.

 

그중 하나는 Object.create() 를 사용하는 방법과 ES6 두가지가 존재한다.

 


Object.create() 사용

 

Object.create() 는 포로토타입의 객체 및 속성을 그대로 가져오는 메소드로,

 

상위클래스의 메소드를 하위클래스 메소드로 가져올 수 있다.

 

다만 상위클래스의 constuctor가 복사되어 오기 때문에 하위클래스 constuctor를 따로 지정해 주어야 한다.

 

 

이전 포스팅에서 사용했던 예제를 이용해 보겠다.

 

function Player(name, team, position){
  this.name = name
  this.team = team
  this.position = position
}

player.prototype.homerun = function(num){
    console.log(`${this.name} hit the homerun season ${num}`)
}

프로토타입을 받아오기 위해서 Object.create()를 사용한다.

 

function Lotte(name,team,position){
	Player.call(this, name, team) 
    this.position = position 
  
Lotte.prototype = Object.create(Player.prototype)

const Daeho = new lotte('D.H.LEE', 'Lotte giants', '1B')  

Daeho.homerun(2) // D.H.LEE hit the homerun season 2

Player에 지정했던 homerun이라는 속성을 사용할 수 있다.

 

다만 이렇게 만 적용하게 되면 Daeho 의 인스턴스는 lotte의 인스턴스를 받지만 

 

Daeho의 constructor는 player의 consturcor를 받기 때문에 따로 지정해 주어야 한다.

 

Lotte.prototype.constructor = Lotte

 

constructor를 지정해주어서 사용해야 한다.

 


ES6

 

ES6 class를 통해서도 간단하기 지정할 수 있다.

 

class Player{
  constructor(name, team){
    this.name = name
    this.team = team
  }
  homerun(num){
    console.log(`${this.name} hit the homerun season ${num}`)
  }
}

 

Extands 키워드를 이용하여 상속받아 올 수 있다.

 

class Lotte extends Player {
  constructor(name,team,position) {
    super(name, team)
    this.position = position
  }
  hit(){
    console.log ('hit') 
  }
}

 

super 키워드를 사용하게 되면 call 메소든와 같이 해당 속성을 그대로 받아올 수 있다.

'언어의 기초 > 자바스크립트(Javascript)' 카테고리의 다른 글

Object Prototypes  (0) 2020.05.10
Object Oriental Programming  (0) 2020.05.08
[Javascript] Scope  (0) 2020.05.01
git workflow & conflict 해결  (1) 2020.04.29
[Javascript] 재귀함수 (알고리즘)  (0) 2020.04.23