프로토타입(Prototype)

✒️ 2025-05-23 16:49 내용 수정


프로토타입

JavaScript의 객체가 다른 객체로부터 상속을 받을 때 상속되는 정보를 제공하는 객체


프로토타입 체인

프로토타입이 상속되는 가상의 연결고리

var obj = new Object();

프로토타입 1.png

var arr = new Array(); // 프로토타입이 Array이고, 더 올라가면 Object도 프로토타입으로 가진다.
console.log(arr);

프로토타입 2.png


프로토타입 생성

function Computer(name, os) {
	this.name = name;
	this.os = os;
	this.poweron = function() {
		console.log('전원이 켜집니다.');
	}
}

var myCom = new Computer('one', 'windows'); // myCom의 프로토타입은 Computer

property 다루기

1. 생성자에 추가하기

function Computer(name, os) {
	this.name = name;
	this.os = os;
	this.memory = '16GB'; // 새로 추가된 property
	this.poweron = function() {
		console.log('전원이 켜집니다.');
	}
}

var myCom = new Computer('one', 'windows');
console.log(myCom);

프로토타입 3.png

2. prototype property 사용하기

function Computer(name, os) {
	this.name = name;
	this.os = os;
	this.memory = '16GB'; // 새로 추가된 property
	this.poweron = function() {
		console.log('전원이 켜집니다.');
	}
}

var myCom = new Computer('one', 'windows');
Computer.prototype.cdrive = '500GB';

console.log(myCom);

프로토타입 4.png