Search code examples
javascriptjqueryextend

jQuery.extend() and jQuery.fn.extend() are the same… Right?


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()?


Solution

  • $.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