Prototype Chain
const car = {
wheels: 4,
drive() {
console.log("drive..");
},
};
const bmw = {
color: "red",
navication: 1,
}
const benz = {
color: "black",
}
const audi = {
color: "blue",
}
bmw.__proto__ = car;
benz.__proto__ = car;
audi.__proto__ = car;
console.log(bmw);
console.log(bmw.wheels);
console.log(benz);
console.log(audi);
bmw
에 wheels
프로퍼티를 찾음
- 없기에
__proto__
안에서 찾음 -> 있다!
- car를 상속 받음
Constructor
const Bmw = function(color) {
this.color = color;
this.wheels = 4;
} ;
Bmw.prototype.wheels = 4;
Bmw.prototype.drive = function () {
console.log("drive..");
};
const x5 = new Bmw("red");
const z4 = new Bmw("red");
- 객체 x5, z4에 각각
__proto__
를 설정하는 것이 아니라
Bmw.prototype
로 중복 코드를 줄일 수 있다.