상속 & prototype

Hunter Joe·2024년 9월 8일

Prototype

const user = { name : "hunter"};

console.log(user.hasOwnProperty('name')); // true
console.log(user.hasOwnProperty('age')); // false

hasOwnProperty라는 프로퍼티를 만든적 없는데 어디서 나왔을까?

일단 객체에서 프로퍼티를 읽으려하는데 없으면 ProtoType여기서 찾는다.

const user = { 
  name : "hunter",
  hasOwnProperty : function() {
  	console.log("hello");
  }
};

console.log(user.hasOwnProperty()); // hello

// 프로퍼티가 존재하면 탐색을 멈춤 (ProtoType까지 안감)

상속

const car = {
  wheels: 4, 
};

const bmw = {
  color : "red",
  logo : "BMW",
};

bmw.__proto__ = car; 

const m3 = {
  color : "white",
  name : "M3",
};

m3.__proto__ = bmw;

// 상속은 계속 체인처럼 연결될 수 있다. (prototype chain) 
// car > bmw > m3
profile
Improvise, Adapt, Overcome

0개의 댓글