简体   繁体   中英

Passing selector or object, what is the best way to convert it into a jQuery object?

I have a function that can be passed a selector, an object, or a jQuery object. What I'm wondering is which method is more efficient in turning that parameter into a jQuery object?

With the following examples, am I better off with:

myFunction = function (obj) {
  var $obj = (obj instanceof jQuery) ? obj : $(obj);
};

or just skipping the conditional and putting the parameter into jQuery like:

myFunction = function (obj) {
  var $obj = $(obj);
};

When you put a jQuery object into the jQuery wrapper, it is still a jQuery object. So I'm mainly wondering is there a cost to doing that instead of the added test in the first example?

is there a cost to doing that instead of the added test in the first example?

Yes, there is a cost -- but not a big one.

Tracing the execution of jQuery from the source code , jQuery will return new jQuery.fn.init( selector, context ); .

The init function will check the following:

  • Is the selector passed a string ? ...
  • Is the selector passed a DOMElement ? ...
  • Is the selector passed a Function ? ...
  • None of the above? Then return jQuery.makeArray( selector, this );

In turn, makeArray will create a new array and merge the contents of the given object (which in this case is a jQuery object, which is considered "array-like").

Finally, this new array will be returned.

It's up to you to decide if the steps above will be problematic for your application, but in practical terms, there's no step above that implies any sort of performance issue -- it should execute extremely fast.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM