2010-07-13 2 views
1

자바 스크립트의 프로토 타입 구문에 익숙하지 않아 매우 간단 할 수 있습니다. 이벤트 trigging 객체 메소드가 객체를 잃습니다.

function MyClass(){ 
    this.init = function(input){ 
     this.input.onkeyup = function(){ 
     this.change(); 
     } 
    } 
} 

은 분명히 여기 몇 가지 탈락했지만, this.input는 HTML input 요소를 참조. 여기서 문제는 this.change()은 더 이상 MyClass의 인스턴스가 아니라 HTML 요소를 나타냅니다. 요소 대신 객체를 가져올 수 있습니까?

답변

1

이벤트 처리기는 이벤트가 발생하는 요소에 자동으로 this 키워드를 지정합니다. ECMA-262 5 판은 특정 개체에 기능을 "결합"이전 기술을 구현하여이 같은 상황에 대처하기 위해 시도합니다

// From Prototype.js 
if (!Function.prototype.bind) { // check if native implementation available 
    Function.prototype.bind = function(){ 
    var fn = this, args = Array.prototype.slice.call(arguments), 
     object = args.shift(); 
    return function(){ 
     return fn.apply(object, 
     args.concat(Array.prototype.slice.call(arguments))); 
    }; 
    }; 
} 

사용법 :

function MyClass(){ 
    this.init = function(input){ 
     this.input.onkeyup = (function(){ 
     this.change(); 
     }).bind(this); 
    } 
} 

ECMA 스크립트 구현과 동일 PrototypeJS implementation (위 코드는 위)

또한 클래스 별 기준을 구현할 수 :

function MyClass(){ 
    this.bind = function(){ 
     var args = Array.prototype.slice.call(arguments), 
      self = this, 
      fn = args.shift(); 
     return function(){ 
     return fn.apply(self, 
      args.concat(Array.prototype.slice.call(arguments))); 
     }; 
    }; 
    this.init = function(input){ 
     this.input.onkeyup = this.bind(function(){ 
     this.change(); 
     }); 
    } 
} 

구식 ;-) 옵션은 함수의 this 외부에 대한 참조를 저장하는 것입니다 :

function MyClass(){ 
    var self = this; 
    this.init = function(input){ 
     this.input.onkeyup = function(){ 
     self.change(); 
     } 
    } 
} 
+0

해야하는이 클로저를 사용하는 대신에 선호되는 방법일까요? –

+0

@Felix Kling : 분명히 그렇게 생각합니다. 특히 많이하는 경우에 특히 그렇습니다. 응답을 더 완전하게 만들기 위해 클로저 솔루션을 추가했습니다. –

+1

감사! 모든 좋은 해결책. 나가 그것을 필요로하는 1 개의 장소에서만이기 때문에 나는 고풍 버전에 지금 갈 것이라는 점을 생각하십시오. – Martin

관련 문제