기본 타입에 기능을 추가하면,
해당 타입을 프로토타입 연결로 가진 모든 객체는 추가된 기능을 사용할 수 있다.
// 함수 이름을 출력하는 메소드 추가
Function.prototype.printFnName = function(){
console.log(this.name);
}
// 함수 생성시 사용가능
function anonym(){}
anonym.printFnName(); // anonym
여러 메소드를 추가하고자 하는 경우 "Function.prototype.~" 이라고
길게 작성할 필요가 없도록 하는 방법이 있다.
// 메소드를 추가하는 메소드
Function.prototype.addMethod = function(name, fn){
if(!this.prototype[name]){ // 메소드 중복 확인
this.prototype[name] = fn; // 메소드 추가
}
};
위 메소드를 먼저 추가함으로써,
앞으로는 메소드를 추가할 때 "Function.~" 으로 더 간략히 작성할 수 있게 되었다.
이제 아래와 같은 방법으로 메소드 추가가 가능하다.
// 숫자형에서 정수만 추출하는 메소드
Number.addMethod('toInteger',function(){
return Math[this < 0 ? 'ceil' : 'floor'](this);
});
(-5/2).toInteger() // -2
// 문자열의 양 끝 빈칸을 지우는 메소드
String.addMethod('trim', function(){
return this.replace(/^\s+|\s+$/g, '');
});
var text = " String ";
text.trim(); // "String"

