PROTOTPY

마데슾 : My Dev Space·2019년 10월 1일
0

[CODESTATES]PRE

목록 보기
4/19

PROTOTPY

  • 인스턴스가 생성(instantiation)될 때 원형(original form), 즉 프로토타입의 모양대로 인스턴스가 생성

  • 인스턴스 메소드는 Object.prototype.something으로 표현
    ' prototype === 원형 '

    ex) prototype은 붕어빵틀, instance는 붕어빵에 비유할 수 있다.

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

  • 예제 1
Number.prototype.invert = function() {
  return -(this);
}

let num = 5;
num.invert() // -5

: 예제2에서 this는 5(숫자 자체)이다.

  • 예제 2
Array.prototype.pluck = function(propertyName) {
  return this.map(function(el) {
    return el[propertyName];
  })
}
let arr = [
  {first : 'heaeun', last : 'yoon'},
  {first : 'daeun', last : 'yoon'}
];
arr.pluck('first'); // ["heaeun", "daeun"]

: 예제2에서 this는 arr이다.

  • 예제 3
Array.prototype.hello = function() {
  console.log('world');
}
let arr = ['code', 'states']
arr.hello() // world
let info = ['heaeun', 'daeun']
info.hello() // world

: 원형객체에 메소드를 추가하게 되면 원형의 모든 인스턴스에도 적용이 된다.
: 프로토타입 개념을 익히거나 혼자 작업할 경우에만 사용하고 협업하는 프로젝트에서는 사용하지 않는게 좋다.

트위틀러에도 위와 같은 방법이 적용된 코드가 있었다는 사실을 이번 강의를 듣고 알았다..ㅎㅎ..
바로 아래의 코드 2개!

Number.prototype.padLeft = function() {
  if(this < 10) {
    return '0' + String(this);
  } else {
    return String(this);
  }
}
let num = 1;
num.padLeft(); // "01"

: 위의 코드에서 this는 num
: 숫자가 10보다 작을때 0을 붙여 반환해주는 함수 코드
이렇게 하면 Number 클래스의 모든 Instance에 적용이 된다 !

Date.prototype.format = function() {
  var yyyy = this.getFullYear();
  var month = (this.getMonth() + 1).padLeft();
  var dd = this.getDate().padLeft();
  var HH = this.getHours().padLeft();
  var mm = this.getMinutes().padLeft();
  var ss = this.getSeconds().padLeft();

  var format = [yyyy, month, dd].join('-') + ' ' + [HH, mm, ss].join(':');
  return format;
}
let date = new Date();
date.format() // "2019-10-01 18:17:32"

: 위의 코드에서 this는 date
: this.getDate().padLeft() - this.getDate()가 10보다 작으면 0을 붙여줌.
: getMonth()는 월을 0부터 세기때문에 this.getMonth() + 1을 해준다

html에서 사용하는 class와 이름만 똑같은줄 알았는데 기능도 비슷한 것 같다..!

profile
👩🏻‍💻 🚀

0개의 댓글