2

I was examining the query source code when I came across this:

3730     |  jQuery.extend({
3731-3775|      //code
3776     |  });

And then right after that, I found this:

3778| jQuery.fn.extend({
----|    //code
----| })

These two should be the same because back on line 296 where the extend function is declared, I found this:

296| jQuery.extend = jQuery.fn.extend = function() {

But since they are the same, why would the jQuery team suddenly switch from always using jQuery.extend() to suddenly using jQuery.fn.extend()?

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Progo
  • 3,452
  • 5
  • 27
  • 44
  • 2
    They are not the same, read the documentation. – adeneo Jan 18 '14 at 14:48
  • 2
    $.fn.extend = Merge the contents of an object onto the jQuery prototype to provide new jQuery instance methods. – adeneo Jan 18 '14 at 14:48
  • jQuery.extend = Merge the contents of two or more objects together into the first object. – adeneo Jan 18 '14 at 14:49
  • 1
    the plugin methods(on, val, $('item').map(), etc) are created using `$.fn.extend` where are static methods($.map, $.each, etc) are created using `$.extend` – Arun P Johny Jan 18 '14 at 14:49
  • If they're different, what about the assignment on line 296? – Barmar Jan 18 '14 at 14:51
  • I could definitely mark some of these as correct answers if they were answers... – Progo Jan 18 '14 at 14:51
  • @Barmar it is operating on the context in which it is called upon... in the case of `$.extend()` `this` inside the extend method refer to the `$` object where as `$.fn.extend` `this` refers to the `$.fn` object where all the plugins are stored so the context of the calls are different – Arun P Johny Jan 18 '14 at 14:51
  • @Saravana Oh no! I didn't see that! – Progo Jan 18 '14 at 14:54
  • @Progo: I just wanted to copy [my answer from there](http://stackoverflow.com/a/14819896/1048572) to here :-) – Bergi Jan 18 '14 at 15:20

2 Answers2

3

$.extend simply extends an object

var obj1 = {'name' : 'Progo'};
var obj2 = {'value' : 'stack overflow'};

$.extend(obj1, obj2);

// obj1 is now {'name' : 'Progo', 'value' : 'stack overflow'}

FIDDLE

jQuery.fn.extend extends the jQuery prototype

jQuery.fn.extend({
  turn_red: function() {
    return this.each(function() {
      this.style.color = 'red'
    });
  }
});

// gives you

$('elements').turn_red(); // sets color to red

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388
1

The key difference is here:

// extend jQuery itself if only one argument is passed
if ( length === i ) {
    target = this;
    --i;
}

this will be different depending on whether $.extend or $.fn.extend was called.

Barmar
  • 741,623
  • 53
  • 500
  • 612