-
Javascript Prototype : 상속을 위해Front-end study/Javascript 2023. 3. 9. 18:48
# 모든 객체들의 조상 object
Javascript 에서 protype 은 모든 객체들의 조상 object 다.
Java 의 Object 객체와 같은 개념이다
Javascript 에서 interface나 generic 같은 개념은 없지만
Protype 이란 개념이 있어서 Javascript 에서 객체지향프로그래밍을 가능하게 한다.
결국 상속을 하기 위해 쓰이고 코드를 재사용하기 위해 쓰인다.
//Object 객체에서 상속을 위한 javascript 코드DelonghiEspCoffeeMachine.prototype = Object.create(CoffeeMachine.prototype);Typescript 에서 class 를 작성하고 상속하는 코드를 작성한 후
ES5 버전의 Javascript 에서 어떤 코드로 변환되는지
아래의 사이트에서 확인해보면 prototype 이 나타나는 것을 확인할 수 있다.
https://www.typescriptlang.org/
JavaScript With Syntax For Types.
TypeScript extends JavaScript by adding types to the language. TypeScript speeds up your development experience by catching errors and providing fixes before you even run your code.
www.typescriptlang.org
Playground 로 가서
Lang: TypeScript 를 선택하고
Target: ES5 를 선택한 후
class CoffeeMachine { makeCoffee() { console.log("grind beans and input some water to make coffee"); } } class DelonghiEspCoffeeMachine extends CoffeeMachine { }
위 TypeScript 를 입력하면 바로 번역이 되는데
"use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var CoffeeMachine = /** @class */ (function () { function CoffeeMachine() { } CoffeeMachine.prototype.makeCoffee = function () { console.log("grind beans and input some water to make coffee"); }; return CoffeeMachine; }()); var DelonghiEspCoffeeMachine = /** @class */ (function (_super) { __extends(DelonghiEspCoffeeMachine, _super); function DelonghiEspCoffeeMachine() { return _super !== null && _super.apply(this, arguments) || this; } return DelonghiEspCoffeeMachine; }(CoffeeMachine));
위와 같은 javascript 코드로 번역되고 prototype 코드가 들어가는 것을 확인할 수 있다.
ES2015 부터는 class 코드를 사용할 수 있다.
이렇게 ES2015 부터는 javascript 에서도 class 를 이용 가능하고,
타입스크립트에서는 class 와 interface 를 사용할 수 있기에
prototype 이란 것은 개념은 알되
modern javascript 시대에는 잘 사용되지 않는다고 보면 좋겠다 ~(^.^)~ (
영~~~원히 그랬으면 좋겠어~)'Front-end study > Javascript' 카테고리의 다른 글
Javascript blur 이벤트로 이메일 입력 후 형식 체크 (jquery 활용) (0) 2023.11.10 Javascript keyup 이벤트 시 전화번호에 실시간 하이픈 입력 (jquery 활용) (0) 2023.11.10 Javascript 에 Module 알아요? (0) 2023.03.13 Javascript {...} [...] destructuring assignment : 구조 분해 할당 (0) 2023.03.07 Arrow function expressions (0) 2023.01.26