기본 타입에 기능 추가 – 함수

Function.prototype 메소드를 추가하면 어느 함수에서나 그것을 사용할 수 있다.
이렇게 사용하면 편리하다

/** 아래처럼 method 라는 함수를 추가해 모든 함수에서 method 메소드를 사용할 수 있다
 * method 는 사용되는 객체에 name 이란 이름을 가지고 func 기능을 가진 메소드를 추가한다.
 */

Function.prototype.method = function (name, func){
    this.prototype[name] = func;
    return this;
};
//Number 에 method 를 사용해 integer 메소드를 추가했다
Number.method('integer',function(){
   return Math [ this < 0 ? 'ceil' : 'floor'](this); //ceil:올림 , floor:내림
});
//Number 에 integer 라는 메소드를 추가했으니 앞으로 숫자에 쓰면 된다
console.log((-10/3).integer()); //-3
//다른예제
String.method('trim',function(){
    return this.replace(/^\s+|\s+$/g, '');
});
console.log('"' + ' neat '.trim() + '"');

Function.prototype 은 전역이기 때문에 사용할때 주의해야 된다. 그래서

Fucntion.prototype.method(name,func){
  if(!this.prototye[name]) {
      this.prototype[name] = func;
  }
};

 

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
모든 댓글 보기
0
생각을 나눠주시면 감사해요!x
()
x
Please enter Google Username or ID to start!
Example: clip360net or 116819034451508671546
Title
Caption
File name
Size
Alignment
Link to
  Open new windows
  Rel nofollow