s2-u2)프로토타입과 클래스

강병규·2023년 1월 13일
0

프로토타입

자바스크립트는 프로토타입 기반 언어라고 한다. 여기서 프로토타입은 모든 객체들이 속성들과 메소드를 상속 받기 위한 템플릿으로 기능한다. 이러한 것을 프로토타입 객체를 가진다고 하는데 프로토타입 객체도 다시 상위 프로토타입 객체로부터 속성과 메소드를 상속 받을 수 있고 그 상위 프로토타입 객체도 동일하다.

.prototype

function Game(platform, name, price) {
  this.platform = platform;
  this.name = name;
  this.price = price;
  this.howToPlay = function() {
    console.log(`install ${this.platform}`);
  };
}

const godOfWar = new Game('3인칭 액션게임', '갓오브워', '플레이스테이션');
const diablo = new Game('핵앤슬래시', '디아블로', '배틀넷');

godOfWar.howToPlay(); // 'install 플레이스테이션'
diablo.howToPlay(); // 'install 배틀넷'

위와 같은 코드가 있을때 프로토타입은 객체 생성자 함수를 통해 .prototype.원하는키 = 라는 코드로 설정 할 수 있다.

function Game(platform, name, price) {
  this.platform = platform;
  this.name = name;
  this.price = price;
  
  };
}

Game.prototype.howToPlay = function(){
	console.log(`install ${this.platform}`);
}

const godOfWar = new Game('3인칭 액션게임', '갓오브워', '플레이스테이션');
const diablo = new Game('핵앤슬래시', '디아블로', '배틀넷');

godOfWar.howToPlay(); // 'install 플레이스테이션'
diablo.howToPlay(); // 'install 배틀넷'

이와 같이 prototype을 통해 생선된 howToPlay라는 코드가 작동을 확인 할 수 있다.

.proto


class Game{
	constructor(platform,name,price){
    	this.platform = platform;
        this.name = name;
        this.price = price;
    }
    
    howToPlay(){
    	console.log(`install ${this.platform}`);
    }
    
}

const diablo = new Game('핵앤슬래시', '디아블로', '배틀넷');
const godOfWar = new Game('3인칭 액션게임', '갓오브워', '플레이스테이션');

Game.prototype.constructor === Game; // true
Game.prototype === diablo.__proto__; // true
Game.prototype.howToPlay === diablo.howToPlay; // true 			
godOfWar.__proto__ === diablo.__proto__; // true

.proto => 객체가 만들어지기 위해 사용되어진 원형의 프로토타입을 '참조'함

위 코드를 기준으로 설명하자면 Game의 프로토 타입을 통해서 Game의 프로토타입 객체에 접근이 가능하고 'diablo' 또는 'godOfWar' 객체의 proto 를 이용해도 Game의 프로토타입 객체에 접근이 가능하다.

클래스, 인스턴스, 프로토타입의 관계

  • arr= diablo Game = Array로 바꿔본다면 동일하게 작동한다

즉 배열(arr)은 Array 클래스의 인스턴스이며 또한 프로토타입에는 다양한 메서드가 있다.

profile
ㅇㅅㅇ

0개의 댓글