모던자바스크립트 19장 프로토타입 2

연호·2022년 12월 27일
0

모던자바스크립트

목록 보기
15/28

프로토타입 2

  1. 자바스크립트는 객체의 프로퍼티에 접근하려고 할 때 해당 객체에 접근하려는 프로퍼티가 없다면 [[Prototype]] 내부 슬롯의 참조를 따라 자신의 부모 역할을 하는 프로토타입의 프로퍼티를 순차적으로 검색한다. 이를 프로토타입 체인이라 하며 상속을 구현하는 메커니즘이다.
function Person(name){
  this.name = name;
}

//프로토타입 메서드 
person.prototype.sayHello = function () {
  console.log(`Hi! My Name is ${this.name}`);
};

const me = new Promise("Lee");

console.log(me.hasOwnProperty('name')); // true
  1. me.hasOwnProperty와 같이 메서드를 호출하면 다음과 같은 과정을 거쳐 메서드를 검색한다. 프로퍼티도 마찬가지
    2-1 호출한 me 객체에서 hasOwnProperty메서드를 검색한다. me 객체에는 hasOwnProperty 메서드가 없으므로 프로토타입 체인을 따라, [[Prototype]] 내부 슬롯에 바인딩 되어있는 프로토타입으로 이동해 hasOwnProperty 메서드를 검색한다.
    2-2 상위 프로토타입인 Person.prototype 에도 hasOwnProperty메서드가 없으므로 상위 프로토타입, Object.prototype으로 이동하여 hasOwnProperty 메서드를 검색한다.
    2-3 Object.prototype에는 hasOwnProperty 메서드가 존재한다. Object.prototype의 hasOwnProperty메서드를 호출한다.

  2. 프로토타입 프로퍼티와 같은 이름의 프로퍼티를 인스턴스에 추가하면 프로토타입 체인을 따라 프로퍼티를 검색하는게 아니라 인스턴스 프로퍼티에 추가한다. 아래 인스턴스 메서드 sayHello는 프로토타입 메서드 sayHello를 오버라이딩했고, 이러한 상속 관계에 의해 프로퍼티가 가려지는 현상을 프로퍼티 섀도잉이라 한다.

const Person = (function (){
  function Person(name){
    this.name = name;
  }
  
  Person.prototype.sayHello = function (){
    console.log(`Hi! My name is ${this.name}`);
  };
  
  return Person;
}());

const me = new Person('Lee');

me.sayHello = function(){
  console.log(`Hey! My name is ${this.name}`);
};

//인스턴스 메서드가 호출된다. 프로토타입 메서드는 인스턴스 메서드에 의해 가려진다.
me.sayHello(); // Hey! My name is Lee
  1. 프로토타입은 임의로 다른 객체로 변경할 수 있다. 이러한 특징을 활용하여 객체 간의 상속 관계를 동적으로 변경할 수 있다.
const Person (function(){
  function Person(name){
    this.mane = name;
  }
  
  //생성자 함수의 prototype 프로퍼티를 통해 프로토타입을 교체
  Person.prototype = {
    sayHello() {
      console.log(`Hi! My name is ${this.name}`);
    }
  };
  
  return Person;
}());

const me = new Person('Lee');

// 프로토타입을 교체한 객체 리터러에는 constructor 프로퍼티가 없다. 따라서 me 객체의 생성자 함수를 검색하면 Person이 아닌 Object가 나온다. 
  1. 프로로타입은 생성자 함수의 prototype 프로퍼티뿐만 아니라 인스턴스의 __proto__접근자 프로퍼티를 통해 접근할 수 있다.

  2. instanceof 연산자는 우변의 생성자 함수의 prototype에 바인딩된 객체가 좌변의 객체의 프로토타입 체인 상에 존재하면 true로, 그러지 않으면 false로 평가된다. instancof 연산자는 생성자 함수의 prototype에 바인딩된 객체가 프로토타입 체인 상에 존재하는지를 확인한다.

function Person(name) {
  this.name = name;
}

const me = new Person('Lee');

// Person.prototype이 me 객체의 프로토타입 체인 상에 존재하므로 true로 평가.
console.log(me instanceof Person); //true

// Object.prototype이 me 객체의 프로토타입 체인 상에 존재하므로 true로 평가.
console.log(me instanceof Object); //true
  1. Object.create 메서드의 첫 번째 매개변수에는 생성할 객체의 프로토타입으로 지정할 객체를 전달한다. 두 번째 매개변수에는 생성할 객체의 프로퍼티 키와 프로퍼티 디스크립터 객체로 이뤄진 객체를 전달하면 명시적으로 프로토타입을 지정하여 새로운 객체를 생성한다. 이를 직접 상속이라한다. 이 메서드의 장점은
    7-1 new 연산자가 없이도 객체를 생성할 수 있다.
    7-2 프로토타입을 지정하면서 객체를생성할 수 있다.
    7-3 객체 리터럴에 의해 생성된 객체도 상속받을 수 있다.
let obj = Object.create(null);
console.log(Object.getPrototypeOf(obj) === null); // true

// obj = {}; 와 동일하다
obj = Object.create(Object.prototype);
console.log(object.getPrototypeOf(obj) === Object.prototype); // true
  1. ES6 에서는 객체 리터럴 내부에서 __proto__ 접근자 프로퍼티를 사용하여 직접 상속을 구현할 수 있다.
const myProto = { x : 10 };

// 객체 리터럴에 의해 객체를 생성하면서 프로토타입을 지정하여 직접 상속받을 수 있다.
const obj = {
  y : 20,
  __proto__ : myProto
  //객체를 직접 상속 받는다.
  //obj => myPtoyo => Object.prototype => null
};
  1. 정적 프로퍼티/메서드는 생성자 함수로 인스턴스를 생성하지 않아도 참조/호출할 수 있는 프로퍼티/메서드를 말한다. 아래의 Person 생성자 함수는 객체이므로 자신의 프로퍼티/메서드를 소유할 수 있고 이를 정적 프로퍼티/메서드라고 한다. 정적 프로퍼티/메서드는 생성자 함수가 생성한 인스턴슬 참조/호출할 수 없다.
function Person(name){
  this.name = name;
}

Person.prototype.sayHello = function(){
  console.log(`Hi! My name is ${this.name}`);
};

//정적 프로퍼티
person.staticProp = 'static prop';

//정적 메서드

Person.staticMethod = function (){
  console.log('staticMethod');
}

const me = new Person('Lee');

// 생성자 함수에 추가한 정적 프로퍼티/메서드는 생성자 함수로 참조/호출한다.
Person.staticMethod(); // staticMethod

// 정적 프로퍼티/메서드는 생성자 함수가 생성한 인스턴스로 참조/호출할 수 없다.
// 인스턴스로 참조/호출할 수 있는 프로퍼티/메서드는 프로토타입 체인 상에 존재해야한다.
me.staticMethod(); // TyepError
  1. in 연산자는 객체 내에 특정 프로퍼티가 존재하는지 여부를 확인한다.
const person = {
  name : "Lee",
  address : "Seoul"
};

console.log("name" in person); // true
console.log("address" in person); // true
// person 객체에 age 프로퍼티가 존재하지 않는다.
console.log("age" in person); // false
  1. for ... in 문은 객체의 프로토타입 체인 상에 존재하는 모든 프로토타입의 프로퍼티 중에서 프로퍼티 어트리뷰트 [[Enumerable]]의 값이 true 인 프로퍼티를 순회하며 열거한다. 하지만 열거할 때 순서를 보장하지 않으니 주의하자.
const person = {
  name : 'Lee',
  address : 'Seoul',
  __proto__ : { age : 20}
};

for (const key in person) {
  console.log(key + ':' + person[key]);
}
// name : Lee
// address : Seoul
// age : 20
profile
뉴비

0개의 댓글