Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
810 views
in Technique[技术] by (71.8m points)

javascript - callback with `this` confusion

I have this clock object:

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

      advance();
      this.interval = setInterval(function () {
        advance();
      }, 5000);
    },

    pause: function () {
      $('#btnScrollPause').hide();
      $('#btnScrollResume').show();
      this.reset();
    },

    resume: function () {
      if (!this.interval) {
        this.start();
      }
    },

    reset: function () {
      clearInterval(this.interval);
      delete this.interval;
    }
  };

I have two buttons that pause and resume automatic scrolling of an element, but my confusion is on the click handlers that I've attached to them.

If I call the pause function like this:

// 1
$('#btnScrollPause').click(function () {
  Clock.pause();
});

It works correctly, however if I try to reduce the code like so:

// 2
$('#btnScrollPause').click(Clock.pause);

It no longer works and I get the error "this.reset is not defined". Also, if I make a function and use that in the click handler instead:

// 3
$('#btnScrollPause').click(scrollPause);

function scrollPause() {
  Clock.pause();
}

It works! Can someone explain why 1 and 3 work, but 2 doesn't?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...