添加事件侦听器后的原型继承问题

时间:2013-07-27 12:12:21

标签: javascript inheritance prototype prototypal-inheritance

如何访问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对象的属性中可用?

1 个答案:

答案 0 :(得分:2)

您必须将eventshandleEvent或两者的定义移到构造函数中,这样您才能获得正确的范围来捕获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直接放入原型中不在另一个对象