2011-11-01 2 views
0
function test() { 
    this.str = "hello"; 

    this.sayHello = function() { 
     document.write(this.str); 
    } 

    this.init = function() { 
     document.onkeydown = this.sayHello; 
    } 
} 

var testing = new test(); 
testing.init(); 

위 코드는 onkeydown 이벤트에 "hello"를 출력해야합니다. 하지만 "정의되지 않음"입니다. 어떻게 작동시킬 수 있습니까?이벤트로 객체 변수 얻기

답변

2

문제는 this.sayHello입니다. keydown에서 sayHello 함수에 대한 참조를 할당하면 컨텍스트 (객체)에 대한 참조가 손실됩니다. 키를 누를 때 콜백으로 호출 될 때, thisDocument 객체를 참조 : 당신은, 값이 기록 된 볼 것이다 당신이 document 개체의 str 변수를 지정한 경우

document.onkeydown(); // or for simplicity imagine - document.sayHello(); 

document.str = "hello"; 

그러나 그것은 당신이 원하는 것이 아닙니다. 해당 객체에 대한 컨텍스트를 보존하려면 다른 함수 안에 keydown 이벤트 핸들러를 래핑해야합니다. 이것에 대해 갈 두 가지 방법. 이벤트 처리기를 다른 함수 안에 넣고 여기에 대한 참조를 유지할 수도 있습니다.

this.init = function() { 
    var me = this; 
    document.onkeydown = function() { 
     me.sayHello(); 
    }; 
} 

또는, 당신은 최신 브라우저를 사용하는 경우,이 이미 bind 기능을 사용하여 ECMAScript를 5로 통합되었습니다.

this.init = function() { 
    var me = this; 
    document.onkeydown = this.sayHello.bind(this); 
} 
+0

정확히 내가 무엇을 찾고 있었는지. 고마워요! –