问题
We all know it's good to cache calls to the DOM, so instead of calling $('#someElement') more times, just save it to a var $someElement and use that.
But is it the same when using $(this) inside an event listener for example? Should $(this) be cached?
Thank you.
回答1:
Each time you call $(this)
or $(selector)
it is a function call to create a new jQuery object... so if you have already created it once, caching will save calling a function to create the same object again
回答2:
If you call $(this)
multiple times, it is better to do something like var $this = $(this);
回答3:
If you refer to the same element later in the event function, yes. Outside of the function it doesn't make any sense to do so because the value of this
will have changed.
来源:https://stackoverflow.com/questions/9603290/caching-this-in-jquery-is-a-best-practice