Javascript get reference to parent object/class from event handler

前端 未结 4 844
慢半拍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:08

    You need to bind the function's context; otherwise this will be the global object:

    $('element').click($.proxy(this.eventHandler, this));
    

    In a modern browser you can also use Function.prototype.bind:

    $('element').click(this.eventHandler.bind(this))
    

提交回复
热议问题