Search

TIL#210802 | javascript 프로토타입 prototype

subtitle
Today I Read | learn 까지는 아니고.
Tags
자바스크립트
TIL
Created
2021/08/02
2 more properties

이거보고 정리

prototype 확인

Object.getPropertyof(value)
JavaScript
복사
example: nest.js > isPlainObject 함수
/* value가 {}인지 확인한다 */ const isPlainObject = (value: any): value is object => { if (!isObject(value)) return false; // 객체의 프로토타입 확인 const proto = Object.getPrototypeOf(value); if (proto === null) return true; // {} === { __proto__: null } // ...후략 };
TypeScript
복사

prototype 체인

객체의 프로퍼티를 참조할 때 해당 프로퍼티가 객체에 없으면 객체의 프로토타입에서 찾는다. 프로토타입에도 없으면 더 위에 있는 프로토타입에서 찾는다. 이것을 프로토타입 체인이라 하며, 자바스크립트에선 이를 이용해 상속과 확장을 구현한다. 덧붙여서, 만약 Object 프로토타입에도 찾는 프로퍼티가 없으면 undefined를 반환한다. 왜냐면 Object 프로토타입이 최상위 객체라서 더 이상 찾을 대상이 없기 때문. - 놀이터흙이제맛 (noritersand.github.io)
객체 프로퍼티 → 프로토타입 → 더 상위 프로토타입 → 최상위 프로토타입(Object) → undefined
example
function Fruit() {} let berry = new Fruit(); berry.__proto__ === Fruit.prototype // true berry.__proto__.__proto__ === Object.prototype; // true berry.__proto__.__proto__.__proto__ === null; // true
TypeScript
복사
source: 놀이터흙이제맛 (noritersand.github.io)
'참조'할 때만 작동한다.
값에 접근할 때만 프로토타입 체이닝하고
할당할 때는 객체에 프로퍼티가 있으면 덮어씌우고, 없으면 새로 추가한다.

constructor

// berry를 만들어낸 생성자가 Fruit이라는 의미 berry.constructor === Fruit; // true berry.__proto__.constructor === Fruit // true
TypeScript
복사
source: 놀이터흙이제맛 (noritersand.github.io)
Function의 생성자의 생성자의 생성자의 무한 츠쿠요미는 Funtion이다.

Object.prototype과 Object()의 차이

Object.prototype.__proto__는 함수*나 객체를 통해 접근할 수 있다:
Object.getOwnPropertyDescriptors()는 함수나 객체를 통해 접근할 수 없다:

Property Shadowing

프로퍼티 섀도잉: 객체 프로퍼티가 프로토타입의 프로퍼티보다 더 우선시되어 참조된다.
Object.getOwnPropertyDescriptors(object): 프로토타입 체이닝을 통해 프로토타입의 프로퍼티를 조회하는 게 아니라 자신만의 프로퍼티를 조회할 때 사용

프로토타입 상속, 확장

1.
class(IE는 지원 x)
2.
apply + prototype(모든 브라우저에서 사용 가능)