-
prototype 활용Javascript 2020. 4. 27. 14:28반응형
모든 javascript의 객체(Object)들은 Prototype의 속성과 메소드를 상속받는다.
Object.prototype
는 가장 최 상위에 상속받으며, Date, String, Array 등의 프로토 타입을 지정 시 Object의 프로토타입을 상속받는다.
prototype 속성을 통해 메소드나 속성 등을 정의하면 따로 생성자를 작성하지 않고도 사용이 가능하여 편리하다.기본적으로 날짜나 문자열에서 많이 사용하는 prototype의 예를 살펴보면 아래와 같다.
- Date
Date.prototype.getBeforeDays = function(days) { var a = new Date(); a.setDate(a.getDate()+days); return a; }; Date.prototype.getBeforeMonths = function(months) { var a = new Date(); a.setMonth(a.getMonth()+months); return a; }; Date.prototype.format = function(f) { if (!this.valueOf()) return " "; var weekName = ["일요일", "월요일", "화요일", "수요일", "목요일", "금요일", "토요일"], d = this; return f.replace(/(yyyy|yy|MM|dd|E|hh|mm|ss|a\/p)/gi, function($1) { switch ($1) { case "yyyy": return d.getFullYear(); case "yy": return (d.getFullYear() % 1000).zf(2); case "MM": return (d.getMonth() + 1).zf(2); case "dd": return d.getDate().zf(2); case "E": return weekName[d.getDay()]; case "HH": return d.getHours().zf(2); case "hh": return ((h = d.getHours() % 12) ? h : 12).zf(2); case "mm": return d.getMinutes().zf(2); case "ss": return d.getSeconds().zf(2); case "a/p": return d.getHours() < 12 ? "오전" : "오후"; default: return $1; } }); };
- String
/* 글자 복제 @param len 글자수 @desc len 만큼 같은 글자를 늘린다. @example "1".string(5) --> "11111" */ String.prototype.string = function(len){ var s = '', i = 0; while (i++ < len) { s += this; } return s; }
/* Zero Formatting @param len 글자수 @desc len 만큼 0으로 채운다 */ String.prototype.zf = function(len){ return "0".string(len - this.length) + this; }; Number.prototype.zf = function(len){ return this.toString().zf(len); };
반응형'Javascript' 카테고리의 다른 글
window.console 확장 (0) 2020.04.29 브라우저 체크 (0) 2020.04.27 Array.reduce 활용 (0) 2020.04.27 UUID 사용 (0) 2020.04.27 - Date