Javascript get reference to parent object/class from event handler

前端 未结 4 851
慢半拍i
慢半拍i 2020-12-16 19:36

I have a class (or function-containing object; I\'ve heard that there is no such thing as a Javascript class) called Foo, with an event handler that is attached to a click e

4条回答
  •  醉酒成梦
    2020-12-16 20:01

    function Foo() {
       this.num=0;
       $(document).on('click', 'element', this, this.eventHandler);
       this.eventHandler=function(e) {
          var _this = e.data; 
          _this.num++;
       }
    }
    

    1) Use JQuery on() method to attach event listeners. 2) Use a reference _this for accessing parent class.

提交回复
热议问题