如何访问this
对象的events
属性中的根Test
:
"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
对象的位置。在我测试之后,我注意到this
在这种情况下将是events
对象。如何以这种方式调整代码以使根对象在events
对象的属性中可用?
答案 0 :(得分:2)
您必须将events
,handleEvent
或两者的定义移到构造函数中,这样您才能获得正确的范围来捕获this
。 />
这是一个例子..
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
直接放入原型中不在另一个对象。