이벤트 처리기는 이벤트가 발생하는 요소에 자동으로 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();
}
}
}
해야하는이 클로저를 사용하는 대신에 선호되는 방법일까요? –
@Felix Kling : 분명히 그렇게 생각합니다. 특히 많이하는 경우에 특히 그렇습니다. 응답을 더 완전하게 만들기 위해 클로저 솔루션을 추가했습니다. –
감사! 모든 좋은 해결책. 나가 그것을 필요로하는 1 개의 장소에서만이기 때문에 나는 고풍 버전에 지금 갈 것이라는 점을 생각하십시오. – Martin