5

If we look at the latest jQuery source at http://code.jquery.com/jquery-latest.js we see the following:

var jQuery = function( selector, context ) {
    // The jQuery object is actually just the init constructor 'enhanced'
    return new jQuery.fn.init( selector, context );
}

My understanding of the new keyword in Javascript is essentially JavaScript passes the function an empty object {} and the function sets stuff on it via this.blah.

Also from my understanding new differs from .call/.apply etc.. in that the return object also has the prototype set to that of the function. So the return value should have a prototype that the same as jQuery.prototype.init.prototype (or jQuery.fn.init.prototype). However from what I see its prototype is set to jQuery.prototype thus all the commands available to work on the set.

Why is this? What am I missing in my understanding?

Crescent Fresh
  • 115,249
  • 25
  • 154
  • 140

2 Answers2

1

If you look deeper into jQuery's code, you'll notice this line:

// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;

This is for readability/structure purposes so the constructor can have its own method.

There's no real "magic" being done here, just standard JavaScript, albeit in a slightly less commonly used way, perhaps. It's useful in jQuery's case since the library is pretty lengthy and this adds good structure/readability to it.

Dan Herbert
  • 99,428
  • 48
  • 189
  • 219
0

In that source file, search for the string "Give the init function the jQuery prototype for later instantiation" :-)

The code sets the prototype reference of jQuery.fn.init to jQuery.prototype (which is the same as jQuery.fn I think).

Pointy
  • 405,095
  • 59
  • 585
  • 614