我是否应该在jQuery中缓存$(this),如果它被多次使用?

前端之家收集整理的这篇文章主要介绍了我是否应该在jQuery中缓存$(this),如果它被多次使用?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我知道如果您多次使用它,您应该缓存选择器的结果.一个例子是:
  1. var $selected = $('.some-selected-element');
  2.  
  3. process($selected);
  4. doStuff($selected);

但如果多次使用缓存$(this),是否有任何性能优势?

  1. $('.some-selector').hover(function () {
  2. if (!$(this).hasClass('some-other-class')) {
  3. $(this).addClass('another-class');
  4. }
  5. process($(this));
  6. }

解决方法

是的,性能提升,因为它可以防止jQuery解释你的选择器.

这是选择器的解释,以及你将绕过的东西. https://github.com/jquery/jquery/blob/master/src/core.js#L78-188

基本上,这部分

  1. if ( selector.nodeType ) {
  2. this.context = this[0] = selector;
  3. this.length = 1;
  4. return this;
  5. }

猜你在找的jQuery相关文章