将$(this)vs缓存选择器用于变量是否有任何性能优势?

Kin*_*rog 1 jquery jquery-selectors

$(this)与缓存选择器相同吗?$(this)每次都会搜索DOM吗?

例如:

$('#selector').on('click', function() {
    $(this).method();
    $(this).method1();
    $(this).method2();

    //OR

    var selector = $('#selector');

    selector.method();
    selector.method1();
    selector.method2();

}
Run Code Online (Sandbox Code Playgroud)

gia*_*our 7

定义$(this)不需要DOM搜索,但它确实在内存中创建了一个新对象.在您的示例中,性能差异可以忽略不计,但使用一个对象而不是创建三个相同的对象仍然是一种好习惯.我经常看到var $this = $(this)- 添加一行可以节省内存和打字,而且任何阅读代码的人都清楚这$this是什么.