gpt4 book ai didi

javascript - 使用 $this 代替 $(this) 是否可以提高性能?

转载 作者:行者123 更新时间:2023-12-03 21:53:27 28 4
gpt4 key购买 nike

假设我有以下示例:

示例一

$('.my_Selector_Selected_More_Than_One_Element').each(function() {
$(this).stuff();
$(this).moreStuff();
$(this).otherStuff();
$(this).herStuff();
$(this).myStuff();
$(this).theirStuff();
$(this).children().each(function(){
howMuchStuff();
});
$(this).tooMuchStuff();
// Plus just some regular stuff
$(this).css('display','none');
$(this).css('font-weight','bold');
$(this).has('.hisBabiesStuff').css('color','light blue');
$(this).has('.herBabiesStuff').css('color','pink');
}

现在,可能是:

示例二

$('.my_Selector_Selected_More_Than_One_Element').each(function() {
$this = $(this);
$this.stuff();
$this.moreStuff();
$this.otherStuff();
$this.herStuff();
$this.myStuff();
$this.theirStuff();
$this.children().each(function(){
howMuchStuff();
});
$this.tooMuchStuff();
// Plus just some regular stuff
$this.css('display','none');
$this.css('font-weight','bold');
$this.has('.hisBabiesStuff').css('color','light blue');
$this.has('.herBabiesStuff').css('color','pink');
}

重点不是实际的代码,而是当$(this)使用超过一次/两次/三次或更多次时的使用。

使用示例二比使用示例一在性能方面是否更好(也许可以解释为什么或为什么不)?

编辑/注释

我怀疑两个更好;我有点担心的是在我的代码中添加了 $this ,而不是当我不可避免地忘记将 $this 添加到时无意中引入了一个潜在的难以诊断的错误一个事件处理程序。那么我应该使用 var $this = $(this) 还是 $this = $(this) 来实现此目的?

谢谢!

编辑

正如 Scott 在下面指出的,这被认为是 jQuery 中的缓存。

http://jquery-howto.blogspot.com/2008/12/caching-in-jquery.html

贾里德

最佳答案

是的,一定要使用$this

每次使用 $(this) 时都必须构造一个新的 jQuery 对象,而 $this 保留相同的对象以供重用。

<小时/>

一个performance test显示$(this)明显$this慢。然而,由于两者每秒执行数百万次操作,因此不太可能产生任何真正的影响,但无论如何重用 jQuery 对象是更好的做法。当选择器(而不是 DOM 对象)被重复传递给 jQuery 构造函数时,真正会产生性能影响 - 例如$('p').

<小时/>

至于var的使用,再次总是使用var来声明新变量。通过这样做,变量只能在声明它的函数中访问,并且不会与其他函数冲突。

<小时/>

更好的是,jQuery 被设计为与链接一起使用,因此请尽可能利用这一点。而不是声明一个变量并多次调用它的函数:

var $this = $(this);
$this.addClass('aClass');
$this.text('Hello');

...将函数链接在一起,无需使用附加变量:

$(this).addClass('aClass').text('Hello');

关于javascript - 使用 $this 代替 $(this) 是否可以提高性能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5724400/

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