Custom Object calling Methods with setTimeout loses scope

后端 未结 3 1375
醉酒成梦
醉酒成梦 2020-12-09 21:10

I\'m having an issue with building a Javascript object, and calling methods within that object using setTimeout. I\'ve tried various workarounds, but always during the seco

相关标签:
3条回答
  • 2020-12-09 21:13

    I can't test this code right now, but does this help?

    setTimeout(function(){triggerSlide(slide1)}, slide1.wait);
    
    0 讨论(0)
  • 2020-12-09 21:17

    This is jQuery, correct? There's a callback parameter to animate(); pass it the function you want called after the animation completes and jQuery will take care of calling it. The callback should capture the scope you want just fine.

    0 讨论(0)
  • 2020-12-09 21:35

    This should be required reading for Javascript programmers getting started with the language (and with Stackoverflow).

    Unlike Java, there's no intrinsic "binding" of functions to any object, regardless of how they're declared. The binding of object context happens only at function invocation time. Thus, when you pass a reference to a function to something like "setTimeout", it doesn't matter at all that you got the function from some object. It's just a function, and "setTimeout" will call it with the default context — the window object.

    There are many ways to handle this (and I won't call it a "problem"; it's a fact of the language, and a very powerful one). If you were using a framework of some kind it'd be easier.

    Another thing: you're binding your timeout and interval handlers as strings containing code. That's a pretty ugly practice, so you should get used to forming function expressions — that is, expressions whose values are functions.

    For your "slideItem" handler, for example, you might do this:

    // ...
    setTimeout(function() { slideItem.changeSlide(); }, 5000);
    

    That way, the function called by the timeout mechanism will always invoke "changeSlide" with your "slideItem" object as the context. You don't need that "self" parameter in "changeSlide" because "this" will point to the right object.

    [edit] I note that you are in fact making some use of jQuery, which is a good thing.

    0 讨论(0)
提交回复
热议问题