Prototype (프로토타입)
TypeScript 는 객체지향 언어이지만 JavaScript 도 ProtoType을 활용하면 객체지향 언어라 할 수 있다. 또한 ES6 에서는 Class 를 사용할 수도 있다.
TypeScript 에서 사용되는 Class나 Interface 를 컴파일러를 이용해서 JavaScript 로 변환하면 결국 다 Prototype 으로 변환이 된다. 그래서 JavaScript 에서 Prototype은 굉장히 근본적인 것이라 볼 수 있는데, 이런 Prototype은 상속을 위해서 사용이 되어진다.
TypeScript 에서는 Class 에 extends
를 통해 상속을 하였다면 JavaScript 에서는 Prototype
을 통해 상속을 구현할 수 있다. (재사용 = 상속)
const x = {};
console.log(x);
/**
-> __proto__: Object
=>
-> constructor: ƒ Object()
-> hasOwnProperty: ƒ hasOwnProperty()
-> isPrototypeOf: ƒ isPrototypeOf()
-> propertyIsEnumerable: ƒ propertyIsEnumerable()
-> toLocaleString: ƒ toLocaleString()
-> toString: ƒ toString()
-> valueOf: ƒ valueOf()
-> __defineGetter__: ƒ __defineGetter__()
-> __defineSetter__: ƒ __defineSetter__()
-> __lookupGetter__: ƒ __lookupGetter__()
-> __lookupSetter__: ƒ __lookupSetter__()
-> get __proto__: ƒ __proto__()
-> set __proto__: ƒ __proto__()
*/
→ x 는 객체로 Object 객체를 상속하고 있다. ( proto: Object )
const array = [];
console.log(array);
/**
-> __proto__: Array(0)
=>
-> concat: ƒ concat()
-> constructor: ƒ Array()
-> copyWithin: ƒ copyWithin()
-> entries: ƒ entries()
-> every: ƒ every()
-> fill: ƒ fill()
-> filter: ƒ filter()
-> find: ƒ find()
-> findIndex: ƒ findIndex()
-> flat: ƒ flat()
-> flatMap: ƒ flatMap()
-> forEach: ƒ forEach()
-> includes: ƒ includes()
-> indexOf: ƒ indexOf()
-> join: ƒ join()
-> keys: ƒ keys()
-> lastIndexOf: ƒ lastIndexOf()
-> length: 0
-> map: ƒ map()
-> pop: ƒ pop()
-> push: ƒ push()
-> reduce: ƒ reduce()
-> reduceRight: ƒ reduceRight()
-> reverse: ƒ reverse()
-> shift: ƒ shift()
-> slice: ƒ slice()
-> some: ƒ some()
-> sort: ƒ sort()
-> splice: ƒ splice()
-> toLocaleString: ƒ toLocaleString()
-> toString: ƒ toString()
-> unshift: ƒ unshift()
-> values: ƒ values()
-> Symbol(Symbol.iterator): ƒ values()
-> Symbol(Symbol.unscopables): {copyWithin: true, entries: true, fill: true, find: true, findIndex: true, …}
-> __proto__: Object
=>
-> constructor: ƒ Object()
-> hasOwnProperty: ƒ hasOwnProperty()
-> isPrototypeOf: ƒ isPrototypeOf()
-> propertyIsEnumerable: ƒ propertyIsEnumerable()
-> toLocaleString: ƒ toLocaleString()
-> toString: ƒ toString()
-> valueOf: ƒ valueOf()
-> __defineGetter__: ƒ __defineGetter__()
-> __defineSetter__: ƒ __defineSetter__()
-> __lookupGetter__: ƒ __lookupGetter__()
-> __lookupSetter__: ƒ __lookupSetter__()
-> get __proto__: ƒ __proto__()
-> set __proto__: ƒ __proto__()
*/
→ array 는 Array객체를 상속하고 있으며, Array객체는 Object 객체를 상속하고 있다.
(=프로토타입 체이닝)