Why does jQuery do this in its constructor function implementation?

Posted by mattcodes on Stack Overflow See other posts from Stack Overflow or by mattcodes
Published on 2010-03-19T12:52:29Z Indexed on 2010/03/19 13:01 UTC
Read the original article Hit count: 245

Filed under:
|

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?

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about JavaScript