1

I was just going through the code of timer.js, playing around with the dev tools in Chrome, and basically I call the plugin like so:

var timer = $.timer(function(){
                $('#add-html').html('Hello There !!');    
            });


            timer.set({ time:5000 , autostart :true });

Even the demo uses the same example, now when the below line executed:

  var timer = $.timer(function(){
                    $('#add-html').html('Hello There !!');    
                });

This line inside the plugin executes and returns this, but what is return this at this point? Is it an instance of the whole plugin? Or what is it exactly, I know without it an error is thrown, but what exactly is return this used here for and what is its value?

I use return this a lot for chaining etc in JavaScript, but somehow I am not able to understand the contextual usage of the return this here. Would anybody explain ?

halfer
  • 18,701
  • 13
  • 79
  • 158
Alexander Solonik
  • 8,718
  • 13
  • 56
  • 133

1 Answers1

2

You should just run this in a debugger (set either a breakpoint or a debugger statement) and evaluate this at that point.

For me, this === jQuery is true on the first run and this instanceof $.timer is true on subsequent runs.

arcyqwerty
  • 8,893
  • 2
  • 40
  • 77
  • hmm... so the plugin is attaching properties to `jQuery` on first run. that seems a little dangerous, for example, it would be overriding the `toggle` method with its own... – Kevin B Oct 05 '15 at 18:37
  • Yes, I didn't write the plugin but usually I see the use of `$.fn.pluginName = function(...)` which creates the plugin on `$.prototype` instead of as a direct property. – arcyqwerty Oct 05 '15 at 18:43
  • $.fn wouldn't make sense here, as that would mean it's attached to an element (which isn't needed here.) It just needs to be separated. Just confirming your findings. – Kevin B Oct 05 '15 at 18:44
  • 1
    Ah, it's not overwriting methods on $.fn, it's overwriting methods on $ directly. so toggle isn't an issue, it's just not a good idea. I doubt the author realizes what it is doing, i'll submit an issue. – Kevin B Oct 05 '15 at 18:45