Javascript 添加事件侦听器后的原型继承问题
如何访问Javascript 添加事件侦听器后的原型继承问题,javascript,inheritance,prototype,prototypal-inheritance,Javascript,Inheritance,Prototype,Prototypal Inheritance,如何访问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.prototy
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.events
指的是Test
对象。在测试之后,我注意到这个
在这种情况下将是事件
对象。如何调整代码,使根对象在事件
对象的属性中可用?您必须将事件
、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.prototype
访问所有内容,我建议您为其中一个对象使用不同的名称,或者直接将handleEvent
放在原型中,而不是放在另一个对象中。我移动了事件的所有道具,包括handleEvent
放在测试对象的根目录中,因为我无法使其正常运行。