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

标签 javascript jquery caching this

假设我有以下示例:

示例一

$('.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/

相关文章:

javascript - 从回调 javascript 函数接收值

javascript - 纯 JavaScript/jQuery/HTML 验证码

javascript - jQuery slider 图像居中建议

javascript - 将 HTML 表格导出到 Excel,表格标题中带有 ID 或类标签

javascript - 在模态框中加载完整的 HTML 页面

caching - 在网站上提供图像和其他静态内容的最快方法(/使加载速度更快)是什么?

javascript - HTML5 缓存行为不当

java - 刷新缓存而不影响访问缓存的延迟

javascript - jqgrid userData 在刷新时发布 null

javascript - 在流程中如何接受异构数组并返回该数组