Is it always best practice to use:
var $this = $(this);
Or is $(this) cached and therefore the above line is just for saving two characters?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Using
$(this)calls at least two (and possibly more than two) functions and allocates an object each and every time you use it (consuming memory that eventually has to be reclaimed). That’s all extra work if you’re just going to reuse the same thing. I’d recommend calling it once and then caching the result (e.g., within the function) rather than having a dozen lines of$(this).foo();$(this).bar();.$is an alias for thejQueryfunction, which looks like this:As you can see, it creates an object, calling the constructor function
jQuery.fn.init. That function then has to figure out what it’s doing, because, jQuery uses thejQueryfunction for 18 different things. I’m not saying it doesn’t do it quickly, but why do all that extra work. 🙂Edit: In the case where you’re passing a DOM element into it (which is usually what
$(this)is doing),jQuery.fn.initdoesn’t make any further function calls. So “just” two plus the allocation.