본문 바로가기
TIL/TIL

Prototype

by koreashowme 2020. 2. 23.

Array.something()
Array.prototype.something()이 둘의 차이점은?


var arr = [1,2,3,4];
arr. isArray(); // does it works?

 

Array. map(function(current, index) {
return current;
}); // does it works?

 

Array. something( )는 Array 클래스에서만 작동
Array. prototype.something( )는 Array 인스턴스에서만 작동.

 

그렇다면 왜 Object. prototype.something와 같이 설명되어 있을까요?

prototype은 무엇을 의미하나요?

 

MEANING OF PROTOTYPE

인스턴스가 생성(instantiation)될 때 원형(original form), 

즉 프로토타입(prototype)의 모양대로 인스턴스가 생성
인스턴스의 메소드는 Object. prototype.something으로 표현
 
prototype === 원형

 

HOW ABOUT class?

JavaScript는 prototype 기반 언어
prototype을 기반으로 객체 지향 프로그래밍(OOP)를 흉내냄
문법적인 편의로 class란 keyword를 도입 (ES6)

 

UNDERSTANDING PROTOTYPE

 

function Car(model, brand) {
  this.model = model;
  this.brand = brand;
}


let spark = new Car("spark", "chevrolet");
let avante = new Car("avante", "hyundai");

-----------------------------------------------------------------------

function Car(model, brand) {
  this.model = model;
  this.brand = brand;
}

Car. prototype.ride = function() {
console. log("vroooom! " + this.model )
};


let spark = new Car("spark", "chevrolet");
spark. ride(); // "vrooom! spark"
let avante = new Car("avante", "hyundai");
avante. ride(); // "vrooom! avante"

 

EXTENDING PROTOTYPE

JavaScript에서 기본적으로 제공되는 객체에 사용자 정의 메소드를
직접 추가할 수 있음 (그러나, 추천하지 않음)
메소드 확장은, 다른 코드와 충돌을 일으킬 수 있음

 

Number.  prototype.invert = function() {
return -(this)

}


let num = 5;

num. invert(); // -5

 

 

Array. prototype.pluck = function(propertyName) {
     return this.map(function(el) {
    return el[propertyName];
  });
}
let arr = [
{ first: "hoyong", last: "lee" },
{ first: "johnny", last: "koo" }
];
arr. pluck("first"); // ["hoyong", "johnny"]

 

 

직접 객체(클래스)를 작성할 때에만, 프로토타입 메소드를 사용하세요.

 

class KEYWORD

class 키워드는 ES6(새로운 자바스크립트 버전)에서 추가됨

 

class Car {
constructor(model, brand) {
    this.model = model;
    this.brand = brand;
}
ride() {
     console.log("vroooom! " + this.model)
   };
}
 let spark = new Car ("spark", "chevrolet");
 spark.ride(); // "vrooom! spark"

 

*/

'TIL > TIL' 카테고리의 다른 글

readLine( ), print( )  (0) 2020.02.29
AJAX *helpful  (0) 2020.02.23
Event Loop & heap & stack  (0) 2020.02.23
비동기, 서버요청, this  (0) 2020.02.23
createElement, instance in JS  (0) 2020.02.18

comment