개념
- JavaScript Prototype
- 자바스크립트 프로토타입
- 모든 자바스크립트 객체가 가진 속성
- 자바스크립트는 프로토타입 기반 언어임
- 객체 생성시 객체 원형인 프로토타입을 이용하여 새로운 객체를 만듦
- 향후, 프로토타입을 통해 객체를 확장함
- 자바스크립트 언어는 클래스를 지원하지 않음 (ES6부터는 지원함)
Object.prototype
- 객체를 생성하면 Object.prototype이 기본적으로 상속됨
function Person(name, age) {
this.name = name;
this.age = age;
}
var person_a = new Person("foo", 10);
console.log(person_a);
- → 브라우저 개발자 모드의 console창에서 확인해보면 아래 그림에서와 같이 __proto__가 기본 상속됨을 확인 할 수 있음
- 원형객체에 속성과 메쏘드를 할당함으로 객체를 생성할 때 생성된 모든 객체에 그 내용이 들어가게됨
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype.gender = "male"; // 생성자의 원형객체에 gender 속성을 할당
Person.prototype.print = function() { // 생성자의 원형객체에 print 메쏘드를 할당
console.log(this.name);
console.log(this.age);
console.log(this.gender);
}
var person_a = new Person("foo", 10);
var person_b = new Person("bar", 11);
person_a.print();
person_b.print();
출력값
foo
10
male
bar
11
male
Object.create
- Object.create() 메쏘드를 통해 객체 상속을 할 수 있음
var a = {a: "Carol"}; // a -> Object.prototype -> null
console.log(a.a); // Carol
var b = Object.create(a); // b -> a -> Object.prototype -> null
console.log(b.a); // Carol
var c = Object.create(b); // c -> b -> a -> Object.prototype -> null
console.log(c.a); // Carol
- 상속 구조를 확인하기위해 console.log를 통해 출력
var a = {a: "Carol"}; // a -> Object.prototype -> null
var b = Object.create(a); // b -> a -> Object.prototype -> null
var c = Object.create(b); // c -> b -> a -> Object.prototype -> null
console.log(a);
console.log(b);
console.log(c);
- → 상속 관계를 개발자 모드에서 분석해 보면 계층 구조로 a는 a -> Object.prototype -> null, b는 b -> a -> Object.prototype -> null 그리고 c는 c -> b -> a -> Object.prototype -> null 인 것을 확인 가능함
프로토타입 체인
- 프로토타입의 연속 상속 관계를 프로토타입 체인이라 함
- 상속값을 참조 할 시 현재 객체에 존재하지 않을 경우 부모 값을 참조 함
var a = {a: 1};
console.log(a.a); // 1
var b = Object.create(a);
b.a = 2;
console.log(b.a); // 2 (현재 객체에 속성 a가 존재함)
var c = Object.create(b);
console.log(c.a); // 2 (현재 객체에 속성 a가 존재하지 않아 부모 객체 값 참조)

