【问题标题】:prototypal inheritance issue after adding event listener添加事件监听器后的原型继承问题
【发布时间】:2013-07-27 12:12:21
【问题描述】:

如何访问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 对象。在我测试之后,我注意到this 在这种情况下将是events 对象。如何以这种方式调整代码以使根对象在 events 对象的属性中可用?

【问题讨论】:

    标签: javascript inheritance prototype prototypal-inheritance


    【解决方案1】:

    您必须将 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 直接放入您的原型中,而不是另一个对象。

    【讨论】:

    • 我移动了 events 的所有道具,包括 handleEventTest 对象的根目录中,因为我无法使其正常运行。
    猜你喜欢
    • 1970-01-01
    • 2020-06-13
    • 2011-12-21
    • 1970-01-01
    • 1970-01-01
    • 2016-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多