블로깅 과제

프로토 타입(object prototype)

lap_mu 2022. 11. 18. 17:08

프로토 타입

  • js는  프로토타입 기반언어라고 불리며 모든 객체들이 메소드와 속성들을 상속받기 위해 프로토타입 객체를 가진다는 의미이다.
  • 프로토타입 객체도 상위 프로토타입의 객체로부터 상속받을 수 있으며 상위 프로토타입 또한 더 상위 프로토타입의 객체로부터 상속을 받을 수 있다. (프로토타입 체인)
  • 상속되는 메소드와 속성은 각각의 객체가 아니라 prototype이라는 속성에 정의되어 있다. 
function Computer(brand, CPU, memory, GPU) {
    this.brand = brand;
    this.CPU = CPU;
    this.memory = memory;
    this.GPU = GPU;
}

Computer.prototype.run = function() {
	// 컴퓨터 전원 ON을 구현하는 코드
}

Computer.prototype.login = function() {
	// 로그인을 구현하는 코드
}
  • 위와 같이 class를 정의할 경우 Computer라는 class만 생기는 것이 아닌 class인 Computer의 prototype 객체도 생겨나게 된다.
  • Computer.prototype은 class인 Computer의 prototype객체를 가리키며 Computer.prototype.constructor는 class인 Computer를 가리킨다.
let myCom = new Computer('DIY', 'i5', '16GB', 'GTX1060');
  • instance를 생성할 때 class인 Computer의 속성과 메소드를 가져오는 것이 아닌 class인 Computer의 prototype의 속성과 메소드를 가져오는 것이다.
  • 위와 같이 instance를 생성해줄 경우 myCom.__proto__는 class인 Computer의 prototype을 가리킨다.