Caching $(this) in jQuery is a best practice?

半世苍凉 提交于 2019-12-30 06:38:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!