[Javascript] 프로토타입-2

개발새발🦶·2022년 11월 28일
1
post-thumbnail

프로토타입의 교체

프로토타입은 임의의 다른 객체로 변경할 수 있다. 부모객체인 프로토타입을 동적으로 변경이 가능하다. 이러한 특징은 객체 간의 상속 관계를 동적으로 변경할 수 있다.

👀 프로토타입은 생성자 함수 or 인스턴스에 의해 교체가 가능하다.



instanceof 연산자

좌변에는 객체, 우변에는 생성자 함수로 받고 우변의 생성자 함수의 prototype에 바인딩된 객체가 좌변의 객체의 프로토타입 체인상에 존재하는지 확인하여 불린 데이터를 반환하는 연산자다.

// 생성자 함수
function Person(name){
  this.name = name;
}

const me = new Person('Lee');

// 프로토타입으로 교체할 객체
const parent = {};

// 프로토 타입의 교체
Object.setPrototypeOf(me, parent);

// Person 생성자 함수와 parent 객체는 노연결
console.log(Person.prototype === parent);   // false
console.log(perent.constructor === Person); // false

// Person.prototype이 me객체의 체인상에 미존재
console.log(me instanceof Person);   // false

// Person.prototype이 me객체의 체인상에 존재
console.log(me instanceof Object);   // true


프로퍼티 열거

for...in 문

객체의 모든 프로퍼티 개수만큼 순회하며 열거하는 메소드이다.
for(변수선언 in 객체){...}

const person = {name:'Lee', address:'seoul'}

for(let key in person){
  console.log(key + ': ' + person[key]);
}

Object.keys/value/entries 메서드

객체 자신의 고유 프로퍼티를 열거 가능한 프로퍼티 키를 배열로 반환한다.

const person = {name:'Lee', address:'seoul', __proto__:{age:20}}

Object.keys(person);    // ['name', 'address']
Object.value(person);	// ['Lee','seoul']
Object.entries(person); // [['name', 'Lee'], ['address','seoul']]
profile
발로하는 코딩 정리기

0개의 댓글