0

를 추가 한 후 어떻게 Test 개체의 events 건물 내부의 루트 this에 액세스 할 수 있습니다프로토 타입 상속 문제 이벤트 리스너

"use strict"; 

var Test = function (element, options) { 


}; 

Test.prototype = { 

    constructor: Test, 

    events: { 

     handleEvent: function (event) { 

      // this.setup() should point to the Test.prototype.setup property 
     }, 

     start: function (event) { 


     } 
    }, 

    setup: function() { 


    } 
}; 

나는 요소에 이벤트 리스너를 추가하려면 다음 구문을 사용 후 :

document.getElementById.addEventListener("touchmove", this.events, false); 

this.eventsTest 개체를 나타냅니다. 테스트를 마치면 thisevents 개체가 될 것으로 나타났습니다. 어떻게 이런 방식으로 코드를 수정하여 events 객체의 속성 내에서 루트 객체를 사용할 수 있습니까?

답변

2

당신은 당신이 this를 캡처 할 수있는 권리 범위를 얻을 수있을 것입니다 그래서 생성자에 events, handleEvent 또는 둘의 정의를 이동해야합니다.
다음은 예입니다 ..

function EO() { 
    this.ev = {  // copy over `handleEvent` and then capture the `this` 
     handleEvent: EO.prototype.ev.handleEvent.bind(this) // with bind 
    }; 
}; 
EO.prototype = { 
    ev: { 
     handleEvent: function (e) { 
      console.log(
       e,     // event 
       this,     // check `this` 
       this.prototype.ev.bar // how to access other properties 
      );}, 
     bar: 'hello!' 
    } 
} 
// construct 
var foo = new EO(); 
// listen 
document.body.addEventListener('click', foo.ev); 

지금 몇 가지 이벤트를 야기하고 올바른 this를 볼 수 있습니다. 당신이 this.prototype을 통해 모든 액세스하는 것을 방지하려면 , 나는 당신이 객체하거나 중 하나에 대한 다른 이름을 사용하는 것이 좋습니다 직접 프로토 타입이 아닌 다른 객체handleEvent을 넣어 것입니다.

+0

나는이 동작을 만들 수 없기 때문에'handle'의 모든 props를'Test' 객체의 루트에 놓았습니다. – Roland