[모던 자바스크립트 딥다이브] 19장 프로토 타입_2

Narcoker·2022년 11월 23일
0

✏️프로토 타입의 교체

부모 객체인 프로토타입을 동적으로 교체할 수 있다.
프로토타입은 생성자 함수 또는 인스턴스에 의해 교체할 수 있다.

생성자 함수에 의한 프로토타입 교체

1 에서 Person.prototype에 객체 리터럴을 할당했다.
이는 Person 생성자 함수가 생성할 객체의 프로토타입을
객체 리터럴로 교체한 것이다.

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

// 1. 생성자 함수의 prototype 프로퍼티를 통해 프로토타입을 교체
   Person.prototype = {
       sayHello() {
           console.log(`Hi! My name is ${this.name`);
       }
   }

return Person;
}());

const me = new Person('Lee');

프로토타입으로 교체한 객체 리터럴에는 constructor 프로퍼티가 없다.
constructor 프로퍼티는 자바스크립트 엔진이 프로토타입을 생성할때
암묵적으로 추가한 프로퍼티이다.

따라서 me 객체의 생성자 함수를 검색하면 Person이 아닌 Object가 나온다.

// 프로토타입을 교체하면 constructor 프로퍼티의 생성자 함수간의 연결이 교체된다.
console.log(me.constructor === Person); // false
// 프로토타입 체인을 따라 Object.prototype의 constructor 프로퍼티가 검색된다.
console.log(me.constructor === Object); // true;

프로토타입을 유지하려면 프로토타입으로 교체한 객체 리터럴에
constructor 프로퍼티를 추가하면 된다.

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

   // 생성자 함수의 prototype 프로퍼티를 통해 프로토타입 교체
   Person.prototype = {
       constructor: Person,
       sayHello() {
           console.log(`Hi! My name is ${this.name`);
       }
   }

return Person;
}());

const me = new Person('Lee');
>> console.log(me.constructor === Object); // false
console.log(me.constructor === Person); // true

인스턴스에 의한 프로토타입 교체

프로토타입은 인스턴스의 __proto__ 접근자 프로퍼티를 통해
교체할 수도 있다.

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

const me = new Person("Lee");

// 프로토타입으로 교체할 객체
const parent = {
  sayHello(){
    console.log(`Hi! My name is ${this.name}`);
   }
};

// 1. me 객체의 프로토타입을 parent 객체로 교체한다.
Object.setPrototypeOf(me, parent);
// 위 코드는 아래의 코드와 동일하게 동작한다.
// me.__proto__ = parent;

me.sayHello(); // Hi! My name is Lee

생성자 함수에 의한 프로토타입의 교체와 마찬가지로 프로토타입으로 교체한 객체에는
constructor 프로퍼티가 없으므로 constructor 프로퍼티와
생성자 함수와의 연결이 파괴된다.

따라서 프로토타입의 constructor 프로퍼티로 me 객체의 생성자 함수를 검색하면
Person이 아닌 Object가 나온다.

console.log(me.constructor === Person); // false
console.log(me.constructor === Object); // true

프로토타입으로 교체한 객체 리터럴에 constructor 프로퍼티를 추가하고
생성자 함수의 prototype 프로퍼티를 재설정하여 파괴된 생성자 함수와
프로토타입 간의 연결을 살리는 방법은 다음과 같다.

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

const me = new Person("Lee");

// 프로토타입으로 교체할 객체
const parent = {
  // constructor 프로퍼티와 생성자 함수간의 연결을 설정
  constructor: Person,
  sayHello(){
    console.log(`Hi! My name is ${this.name}`);
   }
};

// 생성자 함수의 prototype 프로퍼티와 프로토타입 간의 연결을 설정
Person.prototype = parent;

// me 객체의 프로토타입을 parent 객체로 교체한다.
Object.setPrototypeOf(me, parent);
// 위 코드는 아래의 코드와 동일하게 동작한다.
// me.__proto__ = parent;

me.sayHello(); // Hi! My name is Lee

// constructor 프로퍼티가 생성자 함수를 가리킨다.
console.log(me.constructor === Person); // true;
console.log(me.constructor === Object); // false;

// 생성자 함수의 prototype 프로퍼티가 교체된 프로토타입을 가리킨다.
console.log(Person.prototype === Object.getPrototypeOf(me)) // true

이처럼 프로토타입 교체를 통해 객체 간의 상속관계를 동적으로 변경하는 것은 번거롭다.
따라서 프로토타입은 직접교체하지 않는 것이 좋다.
상속 관계를 인위적으로 설정하려면 '직접 상속' 에서 살펴볼 직접 상속이
더 편리하고 안전하다.
또는 ES6에서 도입된 클래스를 사용하면 간편하고 직관적으로 상속관계를 구현할 수 있다.

✏️instanceof 연산자

좌변에는 객체를 가리키는 식별자, 우변에는 생성자 함수를 가리키는 식별자를
피연산자로 받는다.
만약 우변의 피연산자가 함수가 아닌 경우 TypeError 를 발생시킨다.

우변에 생성자 함수에 prototype에 바인딩된 객체가 좌변의 객체의 프로토타입 체인 상에
존재하면 true로 평가되고 그렇지 않은 경우에는 false로 평가된다.

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

const me = new Person('Lee');

console.log(me instanceof Person); // true;
console.log(me instanceof Object); // true;

프로토타입을 교체해보고 결과를 보자

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(parent.constructor === Person); // false

// Person.prototype이 me 객체의 프로토타입 상에 존재하지 않기 때문에 false
console.log(me instanceof Person); // false
// Person.prototype이 me 객체의 프로토타입 상에 존재하기 때문에 true
console.log(me instanceof Object); // true;

me 객체는 비록 프로타입이 교체되어 프로토타입과 생성자 함수간의 연결이 파괴되었지만
Person 생성자 함수에 의해 생성된 인스턴스임은 틀림이 없다.
그러나 me instanceof Person은 false로 평가된다.

이는 Person.prototype이 me 객체의 프로토타입 체인상에 없기 대문이다.
따라서 프로토타입으로 교체한 parent 객체를 Person 생성자 함수에
prototype 프로퍼티에 바인딩하면 me instanceof Person은 true로 평가된다.

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(parent.constructor === Person); // false

// parent 객체를 Person 생성자 함수의 prototype 프로포티에 바인딩한다.
Person.prototype = parent;

// Person.prototype이 me 객체의 프로토타입 상에 존재하기 때문에 true
console.log(me instanceof Person); // true
// Person.prototype이 me 객체의 프로토타입 상에 존재하기 때문에 true
console.log(me instanceof Object); // true;

instanceof 연산자를 함수로 표현하면 다음과 같다.

function isInstanceof(instance, constructor) {
  const prototype = Object.getPrototypeof(instance);
  
  if(prototype === null) return false;

  return prototype === constructor.prototype || isInstanceof(prototype, constructor_;
}

console.log(isInstanceof(me, Person)); // true
console.log(isInstanceof(me, Object)); // true
console.log(isInstanceof(me, Array));; // false

따라서 생성자 함수에 의해 프로토타입이 교체되어 constructor 프로퍼티와 생성자 함수간의 연결이
파괴되어도 생성자 함수의 prototype 프로퍼티와 프로토타입 간의 연결은 파괴되지 않으므로
instanceof는 아무런 영향을 받지 않는다.

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

// 생성자 함수의 prototype 프로퍼티를 통해 프로토타입을 교체
  Person.prototype = {
      sayHello() {
          console.log(`Hi! My name is ${this.name`);
      }
  }

return Person;
}());

const me = new Person('Lee');

// constructor 프로퍼티와 생성자 함수간의 연결이 파괴되어도 instanceof는 아무런 영향을 받지 않는다.
console.log(me.constructor === Person); // false

console.log(me instanceof Person); // true
console.log(me instanceof Object); // true

✏️직접 상속

Object.create에 의한 직접 상속

Object.create 메서드는 명시적으로 프로토타입을 지정하여 새로운 객체를 생성한다.
다른 객체 생성 방식과 마찬가지로 추상연산 OrdinaryObjectCreate를 호출한다.

/** 
/* 지정된 프로토타입 및 프로퍼티를 같은 새로운 객체를 생성하여 반환한다.
/* @params {Object} prototype - 생성할 객체의 프로토타입으로 지정할 개체
/* @params {Object} [properiesObject] - 생성할 객체의 프로퍼티를 갖는 객체
/* @return {Object} 지정된 프로토타입 및 프로퍼티를 갖는 새로운 객체
/*

Object.create(prototype, [, properiesObject];
// 프로토타입이 null 인 객체를 생성한다. 생성된 객체는 프로토타입 체인의 종점에 위치한다.
let obj = Object.create(null);
console.log(Object.getPrototypeOf(obj) === null); // true
// Object.prototype를 상속받지 못한다.
console.log(obj.toString());; // TypeError: obj.toString is not a function

// obj -> Object.prototype -> null
// obj = {}; 와 동일하다.
obj = Object.create(Object.prototype);
console.log(Object.getPrototypeOf(obj) === Object.prototype); // true;

// obj -> Object.prototype -> null
// obj = {x:1}; 과 동일하다.
obj = Object.create(Object.prototype, {
  x: {value: 1, writable: true, enumerable: true, configurable: true}
});
// 위 코드는 아래와 동일하다.
// obj = Object.create(Object.prototype);
// obj.x = 1;
console.log(obj.x); // 1
console.log(Object.getPrototypeOf(Obj) === Object.prototype); // true

const myProto = { x : 10 };
console.log(Object.getPrototypeOf(obj) === Object.prototype); // true

const myProto = { x: 10 };
// 임의의 객체를 직접 상속받는다.
// obj -> myProto -> Object.prototype -> null
obj = Object.create(myProto);
console.log(obj.x); // 10
console.log(Object.getPrototypeOf(obj) === myProto); // true

// 생성자 함수
function Person(name){
   this.name = name;
}
// obj -> Person.prototype -> Object.prototype -> null
// obj -> new Person('Lee') 와 동일하다.
obj = Object.create(Person.prototype);
obj.name = 'Lee';
console.log(obj.name); // Lee
console.log(Object.getPrototypeOf(obj) === Person.prototype); // true

Object.create 메서드의 장점은 다음과 같다.

  • new 연산자가 없이도 객체를 생성할 수 있다.
  • 프로토타입을 지정하면서 객체를 생성할 수 있다.
  • 객체 리터럴에 의해 생성된 객체도 상속받을 수 있다.

참고로 Object.prototype의 빌트인 메서드인 Object.prototype.hasOwnProperty,
Object.prototype.isPrototypeOf, Object.prototype.propertyIsEnumerable 등은
모든 객체의 프로토타입의 종접 즉, Object.prototype의 메서드 이므로
모든 객체가 상속받아 사용할 수 있다.

하지만 ESLint에서는 앞의 예제와 같이 Object.prototype의 빌트인 메서드를
객체가 직접 호출하는 것을 권장하지 않는다. 그 이유는 Object.create 메서드를 통해
프로토타입의 종점에 위치하는 객체를 생성할 수 있기 때문이다.

이 객체는 Object.prototype의 빌트인 메서드를 사용할 수 없다.
따라서 Object.prototype 빌트인 메서드는 다음과 같이 간접적으로 호출하는 것이 좋다.

const obj = Object.create(null);
obj.a = 1;

// Function.prototype.call 메서드는 22장에서 언급한다.
console.log(Object.prototype.hasOwnProperty.call(obj, 'a')); // true

객체 리터럴 내부에서 proto에 의한 상속

Object.create 메서드는 여러 장점이 있지만 두번째 인자로 프로퍼티를 정의하는 번거로웁이 있다.
일단 객체를 생성한 이후 프로퍼티를 추가하는 방법도 있으나 이또한 깔끔하지는 않다.

ES6에서는 객체 리터럴 내부에서 __proto__ 접근자 프로퍼티를 사용하여
직접 상속을 구현할 수 있다.

const myProto = { x: 10 };

// 객체 리터럴에 의해 객체를 생성하면서 프로토타입을 지정하여 직접상속 받을 수 있다.
const obj = {
  y: 20,
  __proto__ : myProto
};

console.log(obj.x, obj.y); // 10 20
console.log(Object.getPrototypeOf(obj) === myProto); // true

✏️정적 프로퍼티/메서드

정적 프로퍼티/메서드는 생성자함수로 인스턴스를 생성하지 않아도 참조/호출 할 수 있다.
정적 프로퍼티/메서드는 인스턴스의 프로토타입 체인에 속하지 않지 때문에 호출할 수 없다.

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(); // TypeError: me.staticMethod is not a function

만약 호출한 인스턴스/프로토타입 메서드 내에서 인스턴스를 참조할 필요가없다면
정적 메서드로 선언해도 인스턴스에서 사용가능하다.

function Foo() {}

Foo.prototype.x = function() {
   console.log('x');
};

const foo = new Foo();
foo.x(); // x

Foo.x = function () {
   console.log('x');
}
Foo.x(); // x

MDN 문서를 보면 다음과 같이 정적 프로퍼티/메서드와 프로토타입 프로퍼티/메서드를 구분하여
설명하고 있기 때문에 구분할 수 있어야한다.
참고로 prototype을 #으로 표기 하는 경우도 있다.
ex) Object.#isPrototypeOf 으로 표기

✏️프로퍼티 존재 확인

in 연산자

in 연산자는 객체 내에 특정 프로퍼티의 존재를 확인한다.
또한 프로토타입 체인 상에 있는 프로퍼티를 모두 검색한다.

const person = {
   name: "lee",
   address: "seoul",
};

// person 객체에 name 프로퍼티가 존재한다.
console.log('name' in person); // true;
console.log('address' in person); // true;
console.log('age' in person); // false;

console.log('toString' in person); // true;

in 대신 ES6에서 도인된 Reflect.has 메서드를 사용할 수도 있다.
in과 동일하게 동작한다.

const person = {
   name: "lee",
};
console.log(Reflect.has(person, 'name')); // true;
console.log(Reflect.has(person, 'toString')); // true;

Object.prototype.hasOwnProperty 메서드

Object.prototype.hasOwnProperty 메서드를 사용해도 객체에 특정 프로퍼티가 존재하는지 알 수 있다.
다만 상속받은 프로퍼티 인 경우 false를 반환한다.

const person = {
   name: "lee",
};
console.log(person.hasOwnProperty('name')); // true;
console.log(person.hasOwnProperty('age')); // false;
console.log(person.hasOwnProperty('toString')); // false;

✏️프로퍼티 열거

for ... in 문

객체의 모든 프로퍼티를 순회하며 열거할때 사용한다.
상속받은 프로퍼티도 순회되나 프로퍼티 어트리뷰트 [[Enumerable]] 이 false이면
순회하지 않는다.

const person = {
   name: "lee",
   address: "seoul",
};

// [[Enumerable]] false
console.log('toString' in person); // true
console.log(Object.getOwnPropertyDescriptor(Object.prototype, "toString"));
// {writable: true, enumerable: false, configurable: true, value: ƒ}

for (const key in person) {
 console.log(key + ': ' + person[key]);
}
// name: lee
// address: seoul

주의할 점은 열거 순서를 보장하지 않는다는 것이다.
다만 대부분의 모던 브라우저에서는 숫자에 대해서는 정렬이 된다.

const obj = {
 2: 2,
 3: 3,
 1: 1,
 b: 'b',
 a: 'a',
}
for (const key in obj) {
 if(!obj.hasOwnProperty(key)) continue;
 console.log(key + ': ' + person[key]);
}
//  1: 1
//  2: 2
//  3: 3
//  b: 'b'
//  a: 'a'

배열에는 for ... in 문을 사용하지말고
일반적인 for문이나 for ... of 문 또는 Array.prototype.forEach 메서드를 권장한다.
배열도 객체이므로 모든 프로퍼티와 상속받은 프로퍼티가 포함될 수 있다.

const arr = [1,2,3];
arr.x= 10;

for (const i in arr) {
// 프로퍼티 x도 출력된다.
 console.log(arr[i]); // 1 2 3 10

for (let i = 0; i < arr.length; i++) {
console.log(value); // 1 2 3
}

arr.forEach(v => console.log(v)); // 1 2 3

for (const value of arr) {
console.log(value); // 1 2 3
}

Object.keys/values/entries 메서드

객체 자신의 고유 프로퍼티만 열거할 때 사용한다.

Object.keys 메서드는 객체 자신의 열거가능한 프로퍼티 키를 배열로 반환한다.

const person = {
   name: "lee",
   address: "seoul",
};

console.log(Object.keys(person)); // ['name', 'address']

ES8에서 도입된 Object.values 메서드는 객체 자신의 열거가능한 프로퍼티 값를 배열로 반환한다.

const person = {
   name: "lee",
   address: "seoul",
};

console.log(Object.values(person)); // ['lee', 'seoul']

ES8에서 도입된 Object.entries 메서드는 객체 자신의 열거가능한 프로퍼티 키 값 쌍 배열을
배열에 담아 반환한다.

const person = {
   name: "lee",
   address: "seoul",
};

console.log(Object.entries(person)); // [['name', 'lee'], ['address', 'seoul']]
Object.entries(person).forEach([key, value]) => console.log(key,value));
// name Lee
// address seoul
profile
열정, 끈기, 집념의 Frontend Developer

0개의 댓글