Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which to use when referencing in jQuery plugins - $(obj) vs obj

I'm self learning and currently tackling jQuery plugins.

I've discovered a boiler plate that for iterating through elements on a page assigns $(this) to a global variable 'obj'.

var obj = $(this);

As a result in my functions I can use either $(obj).someFunc() or obj.someFunc() both work but if honest I don't really understand what the difference is.

So there's the question, what are the performance differences/benefits of both methods and which should I be using?

like image 393
KryptoniteDove Avatar asked May 07 '26 16:05

KryptoniteDove


1 Answers

If obj is already a jQuery object, which is the case when you do var obj = $(this);, then there is no need to pass it to jQuery again.

$(obj) is the same as $($(this)), which is clearly redundant.

Having a look at jQuery's documentation [docs] also helps to understand what you can pass to jQuery (alias $):

  • jQuery( selector [, context ] )
  • jQuery( element )
  • jQuery( elementArray )
  • jQuery( object )
  • jQuery( jQuery object )
  • jQuery()

You see that passing a jQuery object is perfectly valid, but it will clone the passed object, which is probably not what you intend to do.


However, it might be worth pointing out that inside a jQuery plugin method, this is already a jQuery object, so you don't have to pass it to jQuery either.

More info here: http://docs.jquery.com/Plugins/Authoring.

like image 95
Felix Kling Avatar answered May 09 '26 09:05

Felix Kling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!