ES5 JavaScript는 클래스라는 개념이 없었습니다. 그래서 기존의 객체를 복사하여(cloning) 새로운 객체를 생성하는 프로토타입 기반의 언어입니다. 프로토타입 기반 언어는 객체 원형인 프로토타입을 이용하여 새로운 객체를 만들어냅니다. 이렇게 생성된 객체 역시 또 다른 객체의 원형이 될 수 있습니다.

프로토타입은 객체를 확장하고 객체 지향적인 프로그래밍을 할 수 있게 해줍니다. 프로토타입은 크게 두 가지로 해석됩니다. 프로토타입 객체를 참조하는 prototype 속성과 객체 멤버인 proto 속성이 참조하는 숨은 링크가 있습니다.

이 둘의 차이점을 이해하기 위해서는 JavaScript 함수와 객체의 내부적인 구조를 이해 해야 합니다.

1. 함수와 객체의 내부 구조

function Person() {}

속성이 하나도 없는 Person이라는 함수가 정의되고, 파싱단계에 들어가면, Person 함수 Prototype 속성은 프로토타입 객체를 참조합니다. 프로토타입 객체 멤버인 constructor속성은 Person 함수를 참조하는 구조를 가집니다. 여기서 알아야 하는 부분은 Person 함수의 prototype 속성이 참조하는 프로토타입 객체는 new 라는 연산자와 Person 함수를 통해 생성된 모든 객체의 원형이 되는 객체입니다. 생성된 모든 객체가 참조한다는 것을 기억해야 합니다.

function Person() {}

var joon = new Person();
var jisoo = new Person();

(1). var joon = new Person()은 생성자 함수를 할당 하므로 joon은 function Person 을 가리킨다.

(2). joon의 prototype 은 Person생성자의 prototype 을 가리킨다.

joon, jisoo 의 prototype 과 funtion Person 의 prototype은 같다.

(3). Person생성자 prototype 은 Object 생성자 prototype 을 가리킨다.

proto : 상위 객체, 상속하는 객체, 내장 메서드가 여기에 담긴다. 할당 시 object를 할당한다.

const car = {
	// constructor: Bmw,
	wheels: 4,
	drive() {
		console.log("drive..");
	},
};

const Bmw = function(color) {
	this.color = color;
}

const x5 = new Bmw("red");
const z4 = new Bmw("blue");

// 상속 ------
x5.__proto__ = car;
z4.__proto__ = car;
//------------

proto 상위의 proto 상위의 proto 를 Prototype Chain 이라고 한다.

prototype : 함수 객체, 상속하는 함수, 해당 함수의 생성자, 속성 및 메서드 객체 정의, 할당 시 새로운 property를 할당한다.

const Bmw = function(color) {
	this.color = color;
}

// 상속 ------
Bmw.prototype.wheels = 4;
Bmw.prototype.drive = function () {
	console.log("drive..");
};
Bmw.prototype.navigation = 1;
Bmw.prototype.stop = function () {
	console.log("STOP!");
};
//------------

const x5 = new Bmw("red");
const z4 = new Bmw("blue");
const Bmw = function(color) {
	this.color = color;
}

// 상속 ------
Bmw.prototype = {
	constructor: Bmw, // 명시적으로 선언해 주어야 하는 단점
	wheels: 4,
	drive() {
		console.log("drive..");
	},
	stop() {
		console.log("STOP!");
	},
};
//------------

const x5 = new Bmw("red");
const z4 = new Bmw("blue");