[英]Is there any performance benefit to using $(this) vs caching selector to a variable?
Is $(this) the same as caching a selector? $(this)与缓存选择器是否相同? Does $(this) search the DOM everytime?
$(this)每次都搜索DOM吗?
For example: 例如:
$('#selector').on('click', function() {
$(this).method();
$(this).method1();
$(this).method2();
//OR
var selector = $('#selector');
selector.method();
selector.method1();
selector.method2();
}
Defining $(this)
doesn't require a DOM search, but it does create a new object in memory. 定义
$(this)
不需要DOM搜索,但是确实会在内存中创建一个新对象。 In your example, the difference in performance might be negligible, but it's still good practice to use one object instead of creating three identical ones. 在您的示例中,性能的差异可以忽略不计,但是使用一个对象而不是创建三个相同的对象仍然是一种好习惯。 I often see
var $this = $(this)
-- adding that one line saves both memory and typing, and it's clear to anyone reading your code what $this
is. 我经常看到
var $this = $(this)
-补充说,一行可以节省内存和键入内容,任何人读您的代码都可以清楚地知道$this
是什么。
In this context 在这种情况下
$('#selector').on('click', function() {
$(this).method();
$(this).method1();
$(this).method2();
});
'this' is a local variable which refers to the DOM element. “ this”是一个局部变量,它引用DOM元素。 So to answer your questions, this is not doing a 'dom'query every single time.
因此,要回答您的问题,这并不是每次都执行“ dom”查询。 You are however calling $(this) several times, which is passing the 'this' DOM element to the jquery constructor and giving you a jquery object.
但是,您多次调用$(this),这会将'this'DOM元素传递给jquery构造函数,并为您提供jquery对象。 A more optimal way to do this would be as follows:
执行此操作的最佳方法如下:
$('#selector').on('click', function() {
var $this = $(this);
$this.method();
$this.method1();
$this.method2();
});
The second method 第二种方法
$('#selector').on('click', function() {
var selector = $("#selector");
selector.method();
selector.method1();
selector.method2();
});
would be a little more expensive, since $("#selector") would end up doing a DOM query. 由于$(“#selector”)最终会进行DOM查询,因此价格会更高一些。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.