krzyhub
krzyhub

Reputation: 6540

jQuery - $this instead of $(this)?

I think that i read something that said that it is better for code like this:

var id1 = $(this).attr('id') 
var id2 = $(this).parent().parent().parent().parent().parent().attr('id') 
var text = $(this).text()        

..to give one variable like $this = $(this) and then use it instead of every $(this). I don't know where i read this, so my question is that is it true?

Upvotes: 2

Views: 494

Answers (5)

Karl Laurentius Roos
Karl Laurentius Roos

Reputation: 4399

If I got your question right, yes. Here's an example:

var t = $(this);
var id1 = t.attr('id'); 
var id2 = t.parent().parent().parent().parent().parent().attr('id') ;
var text = t.text();

Upvotes: 2

kobe
kobe

Reputation: 15835

Let me add few more points to this

the following is called caching and its used to improve performance in DOM manipulation, the following code will cache the object and won't query the DOM everytime you do any operation on $this.

var $this = $(this);
var id1 = $this.attr('id'); 

the $(this) might be little more expense as everytime it has to do query on DOM

var id1 = $(this).attr('id'); 

Upvotes: 1

Sinan
Sinan

Reputation: 5980

If your question is assigning selectors to local var then you're right. This has something to do with Javascript's scope nature.

If I remember correctly when you use a local var then variable lookup is faster. Especially if you are using a selector multiple times.

I dunno where you read it but I watched a video about this on Google Developer Stuff.

I dont remember the original video but check this video. It is a good watch.

Also check this slide

Upvotes: 1

genesis
genesis

Reputation: 50966

yes you can

var $this = $(this);
var id1 = $this.attr('id'); 
var id2 = $this.parent().parent().parent().parent().parent().attr('id') ;
var text = $this.text();

Upvotes: 1

Xion
Xion

Reputation: 22770

This saves some time on wrapping up the this object in the jQuery array-like collection every time you use it. So short answer: yes, but the difference shouldn't be big.

Upvotes: 2

Related Questions