[자바스크립트] 상속, 프로토타입(Prototype)

kim seung chan·2021년 7월 17일
0

1. hasOwnProperty

const user = {
	name : 'Mike'
}

user.name // "Mike"
user.hasOwnProperty('name') // true
user.hasOwnProperty('age') // false
  • hasOwnProperty은 proto 에 있다.

2. proto

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

const bmw = {
	color: "red",
    navigation: 1,
};

const benz = {
	color: "black"
};

const audi = {
	color: "blue"
};

bmw.__proto__ = car;
benz.__proto__ = car;
audi.__proto__ = car;

bmw.color // red
bmw.wheels // 4 
const car = {
	wheels: 4,
    drive() {
    	console.log("drive..");
    },
};

const bmw = {
	color: "red",
    navigation: 1,
};

bmw.__proto__ = car;

const x5 = {
	color: "white",
    name: "x5"
};

x5.__proto__ = bmw;
  • proto x5에서 찾고 없으면 상속된 bmw에서 찾게 되고 찾는 객체가 없으면 맨 위 car 객체까지 가게된다. 이런 것을 Prototype Chain이라고 한다.
for(p in x5){
	if(x5.hasOwnProperty(p)){
    	console.log('o', p)
    }else {
    	console.log('x', p)
    }
} // o o x x x 가 출력된다
  • hasOwnProperty는 직접 가지고 있는 요소만 출력된다.

3. prototype

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

Bmw.prototype.wheels =4;
Bmw.prototyle.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");
  • z4 instanceof Bmw // true and z4.constructor === Bmw; // true 가되는데 여기서 prototype 을 따로 지정해주지 않으면 false 가 된다.

0개의 댓글