Why does jQuery do this in its constructor function implementation?
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 protot开发者_如何学JAVAype 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?
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.
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).
精彩评论