nonopolarity
nonopolarity

Reputation: 151196

In jQuery, why is $.clone(this) the same as $(this).clone()?

I actually made a mistake in the API call to jQuery's .clone():

Instead of using http://jsfiddle.net/AXsB5/17/ (you need to click in the fiddle to make the .clone() get executed):

$(".foo").click(function() {
    var el = $(this).clone();

    el.css({ color: "orange" });
    $("#bar").append(el);
});

I mistakenly used http://jsfiddle.net/AXsB5/18/:

$(".foo").click(function() {
    var el = $.clone(this);

    $(el).css({ color: "orange" });
    $("#bar").append(el);
});

The jQuery API docs would suggest that it shouldn't work for the second case. I wonder why both cases worked?

Upvotes: 3

Views: 502

Answers (2)

Derek
Derek

Reputation: 4751

According to $ vs $():

Until now, we've been dealing entirely with methods that are called on a jQuery object.

For example:

$( "h1" ).remove();

Most jQuery methods are called on jQuery objects as shown above; these methods are said to be part of the $.fn namespace, or the "jQuery prototype," and are best thought of as jQuery object methods.

However, there are several methods that do not act on a selection; these methods are said to be part of the jQuery namespace, and are best thought of as core jQuery methods.

This distinction can be incredibly confusing to new jQuery users. Here's what you need to remember:

  • Methods called on jQuery selections are in the $.fn namespace, and automatically receive and return the selection as this.

  • Methods in the $ namespace are generally utility-type methods, and do not work with selections; they are not automatically passed any arguments, and their return value will vary.

However, running through the JSFiddle using a debugger, it seems it's never even getting to the clone() method on the $.fn namespace and is actually hitting $().clone(). This is probably due to it mapping $().clone() inside $.clone() (which runs when the jquery file is loaded) like in the source code linked above by Arun P Johny. I hope that makes sense... my advice is just to run through with a debugger to see for yourself.

Upvotes: 4

Arun P Johny
Arun P Johny

Reputation: 388416

It looks like an internal method, not exposed to users(that might by why there is no api doc).

The .clone() method internally uses it, so both are the same

jQuery.clone() and .clone()

clone: function( dataAndEvents, deepDataAndEvents ) {
    dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
    deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;

    return this.map( function () {
        return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
    });
}

Upvotes: 3

Related Questions