我应该将jQuery或DOM对象作为参数传递吗?(表现问题)

Con*_*ton 9 javascript performance jquery function argument-passing

哪个是更好的性能.

foo(this);

function foo(element) {

    $(element).index();

}
Run Code Online (Sandbox Code Playgroud)

或者我应该这样做

foo($(this));

function foo($element) {

    $element.index();

}
Run Code Online (Sandbox Code Playgroud)

显然考虑到我将在函数内部使用该参数几次.

谢谢!康纳

Gua*_*ard 9

如果你打算将它包装在jQuery上,那么将它包装在哪里并不重要.

只有你缓存包装结果并且不包装它两次才重要.

就此而言,以下规则适用于许多插件的代码:

1)jQuery vars都以$为前缀: var $this = $(this)

2)永远不要在$中包装$ -prefixed var

3)总是缓存(保存到var)任何多次使用jQuery包装的表达式

4)如果相同的包装对象(如var $items = $('ul li');)在几个相似的函数中出现不止一次,则将其移动到外部作用域并依赖闭包.


Poi*_*nty 8

如果您正在编写一个将jQuery对象作为参数的函数,那么您应该考虑将其编写为jQuery插件.

jQuery.fn.yourFunction = function(otherArg1, otherArg2, ...) {
  // ...
};
Run Code Online (Sandbox Code Playgroud)

然后而不是写作

yourFunction($(whatever));
Run Code Online (Sandbox Code Playgroud)

你可以写

$(whatever).yourFunction().someOtherJQueryFunction();
Run Code Online (Sandbox Code Playgroud)

在函数内部,this值将是jQuery对象本身.用于大多数常见DOM相关功能的模式是:

jQuery.fn.yourFunction = function(otherArg1, otherArg2, ...) {
  return this.each(function() {
    var $element = $(this);
    // do stuff ...
  });
};
Run Code Online (Sandbox Code Playgroud)

请注意,在函数的外层,this没有包装,$(this)因为它已经保证是一个jQuery对象.在"each()"函数的主体中,或者类似的任何其他内容都不是这种情况.