callback with `this` confusion

前端 未结 2 1488
故里飘歌
故里飘歌 2020-12-21 16:41

I have this clock object:

var Clock = {
    start: function () {
      $(\'#btnScrollPause\').show();
      $(\'#btnScrollResume\').hide();

      advance();         


        
2条回答
  •  温柔的废话
    2020-12-21 16:51

    This is related to how this keyword works in JavaScript. When you pass a method as a callback to another function the method is detached from the object and the this keyword doesn't refer to object. Additionally jQuery event methods modify the this value of callbacks to refer to the owner of the event, i.e. the DOM elements.

    One option that you have is using the .bind function:

    $('#btnScrollPause').click(Clock.pause.bind(Clock));
    

    A related question: How does the “this” keyword work?

提交回复
热议问题