gpt4 book ai didi

jquery - 使用 $(this) 与将选择器缓存到变量相比是否有任何性能优势?

转载 作者:行者123 更新时间:2023-12-01 06:22:39 25 4
gpt4 key购买 nike

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

例如:

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

//OR

var selector = $('#selector');

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

}

最佳答案

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

关于jquery - 使用 $(this) 与将选择器缓存到变量相比是否有任何性能优势?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17865377/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com