'2012/02/25'에 해당되는 글 2건

  1. 2012.02.25 자바스크립트 메서드 빌려쓰기
  2. 2012.02.25 자바스크립트 상속 6

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


객체 메서드 빌려 쓰기

  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 메서드를 빌려 원하는 매개변수를 골라내는 방법이 있습니다.

자바스크립트 상속 6


기타 상속 방식


  1. var Inherit = (function(){
  2.    
  3.     var Parent = {
  4.         name: 'test' ,
  5.         getName: function(){
  6.             return this.name;
  7.         }
  8.  
  9.     }
  10.  
  11.     function Child(){ ; };
  12.  
  13.     Child.prototype = Parent;
  14.     Child.prototype.constructor = Child;
  15.  
  16.     return new Child();
  17.  
  18. })();
  19.  
  20. alert(Inherit.getName()); // test
  21. alert(Inherit.constructor); // Child

1. Parent 객체를 생성 합니다.

2. Child 생성자 함수의 프로토타입 맴버에 Parent 객체를 추가 합니다.

 
3. new Child 객체를 반환 합니다.
 
4. 여기서 new Child 객체는 new Parent 객체의 맴버 모두(name, getName())를 상속
받습니다.


부모 객체를 생성자 함수가 아닌 객체 리터널 방식으로 생성하여 자식 객체에게 상속한
방법 입니다.
prev 1 next