자바스크립트 메서드 빌려쓰기


객체 메서드 빌려 쓰기

  1. function Parent(name){
  2.     this.name = name;
  3. };
  4.  
  5. Parent.prototype.substr = function(s, e){
  6.     return this.name.substr(s, e);
  7. }
  8.  
  9. function method(name){
  10.     this.name = name;
  11.     return this;
  12. }
  13.  
  14. method.prototype.getName = function(s, e){
  15.     // Parent 객체의 메서드 빌려쓰기.
  16.     return new Parent().substr.apply(this, [s, e]);
  17. }
  18.  
  19. alert(new Parent('jsk').substr(0, 1)); // j
  20. alert(new method('jsk').getName(1, 1)); // s

모듈을 작성하다보면 어떤 객체의 메서드 한 두 개만 마음에 드는 경우가 있습니다.
 
이 메서드들을 재사용 하고 싶지만, 해당 객체와 부모-자식 관계까지 만들고 싶지는 않을때
위같은 메서드 빌려쓰기 작성법을 이용하여 원하는 메서드만 골라서 사용할 수 있습니다.


  1. function f(){
  2.     var args = [].slice.call(arguments, 1, 3);
  3.  
  4.     return args;
  5. }
  6.  
  7. alert(f(1, 2, 3, 4)); // 2, 3

가장 대표적인 사례를 뽑자면, 위의 코드에서 처럼 함수의 arguments 객체와 [].slice 메서드를 빌려 원하는 매개변수를 골라내는 방법이 있습니다.