JS 전문가되기 //Day011
1. prototype?
자바스크립트 ES6 문법 이전에, Class 라는 OOP를 위한 도구가 없었을 때
자바스크립트에서 OOP를 흉내낼 수 있었던 도구이다.
let car = { wheels: 4, drive() {console.log("drive...")} };
let bmw = { navigation: 1, color: 'red' };
let x5 = { name: 'x5' };
위처럼 3개의 객체가 존재한다고 해보자. 우리는 __proto__
일명 js prototype 기능을 이용해서 Class 기능과 비슷하게 inheritance가 가능하도록 위 객체들을 만들어볼거다.
let car = { wheels: 4, drive() {console.log("drive...")} };
let bmw = { navigation: 1, color: 'red' };
bmw.__proto__ = car;
let x5 = { name: 'x5' };
x5.__proto__ = bmw;
// result
console.log(x5.color); // 'red'
console.log(x5.wheels); // 4
분명 x5 객체에는 wheels 속성과 color 속성이 없지만, 값이 출력이 되고 있다. 이유가 뭘까?
바로 Prototype Chain 때문이다.
콘솔로그를 입력하자 x5 객체에서 먼저 color 속성값을 찾는다.
그리고 없다는 걸 알고 __proto__
를 이용해서 상위 객체(부모 객체)에서 다시 탐색한다.
있다! 그리고 결과가 출력된다.
이것도 마찬가지이다. !
이처럼 prototype으로 prototype chain을 만들어서 class와 비슷하게 사용할 수 있다.
하지만 이런 방식도 문제가 있다. 코드와 함께 보자.
let car = { 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;
그래서 이 코드를
const Bmw = function(color) {
this.color = color;
};
// POINT
Bmw.prototype.wheels = 4;
Bmw.prototype.drive = function() {console.log('drive...")};
// POINT
const x5 = new Bmw('red');
const z4 = new Bmw('blue');
가운데 포인트 코드줄에 prototype은 무엇이냐면,
"생성자 함수가 생성하는 인스턴스에 __proto__
를 (.wheels, .drive)와 같이
설정한다는 의미입니다."
중복코드를 많이 줄일 수 있겠죠?
그리고 추가로 x5, z4 객체는 생성자 함수가 생성하는 객체기 때문에
인스턴스라고 부릅니다.
이걸 확인하기 위해선 instanceof keyword를 사용하면 됩니다.
z4 instanceof Bmw // true
x5 instanceof Bmw // true
방금 z4, x5의 생성자가 Bmw라고 했습니다. 그러면 이 말은 곧,
인스턴스의 constructor가 생성자라고 했으니 Bmw가 constructor가 되겠네요?
z4.constructor === Bmw // true
x5.constructor === Bmw // true
와! prototype에 대해 모든 것을 끝냈습니다.
다음에는 js 시리즈에서 class라는 주제로 작성해야지
Author And Source
이 문제에 관하여(JS 전문가되기 //Day011), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@315dragon/WHATIS.-PROTOTYPE저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)