프로토타입

Geonil Jang·2021년 7월 27일
0
post-thumbnail

프로토타입

자바스크립트에서는 생성저의 prototype프로퍼티를 통해 타입의 특징을 정의합니다.

  • contructor 메소드는 Object타입의 프로퍼티 이며 prototype에 의해 정의 되었습니다. Object.prototype.constructor
function smell(){
	console.log(`${this.name} food`)
}

function Food(name){
  this.name = name;
  this.smell = function(){
		console.log(`${this.name} food`)
	}
}

const f1 = new Food("pizza");
const f2 = new Food("rice");

console.log(f1.smell === f2.smell) // false; 즉 객체를 생성할 때마다 별개의 함수가 계속 만들어 진다.

같도록 수정해보자

function smell(){
	console.log(`${this.name} food`)
}

function Food(name){
  this.name = name;
  this.smell = smell
}

const f1 = new Food("pizza");
const f2 = new Food("rice");

console.log(f1.smell === f2.smell) // false; 즉 객체를 생성할 때마다 별개의 함수가 계속 만들어 진다.

proto = [[Prototype]]

prototype

인스턴스 에는 [[Prototype]]이 있고 생성작의 protorype을 참조 할 수 있게 되어 있습니다.

Food.prototype.smell = function(){
	console.log(`${this.name} food`)
}

function Food(name){
  this.name = name;
  this.smell = smell
}

const f1 = new Food("pizza");
const f2 = new Food("rice");

console.log(f1.smell === f2.smell) // false; 즉 객체를 생성할 때마다 별개의 함수가 계속 만들어 진다.

프로토 타입 체인

인스턴스에서 생성자의 [[Prototype]]을 타고 올라가면 프로퍼티를 탐색하는 현상.

정리

  • 자바스크립트는 생성자의 prototype 프로퍼티를 통해 타입의 특징을 정의합니다.
  • 모든 인스턴스는 내부에 [[Prototype]] 프로퍼티를 가지면 이를 통해 생성자의 prototype 프로퍼티를 추적합니다.
  • 인스턴스에서 생성자의 [[Prototype]]을 타고 올라가며 프로퍼티를 탐색하는 현상을 프로토타입 체인 이라고 합니다.
profile
takeaways

0개의 댓글