2

Why is the init function in jQuery.prototype? I have put it in jQuery's closure and it works fine. I did this:

(function( window, undefined ) {

    var jQuery = function( selector, context ) {
        return new init( selector, context, rootjQuery );
    }
    var init=function( selector, context, rootjQuery ) {
        ...
    }
    ...
})(...)

Thanks,

Eric J.

ericj
  • 2,138
  • 27
  • 44

1 Answers1

3

We don't know (ask the library maintainers for their design desicions).

But having it available as a public property does allow overwriting or amending the constructor without harming the jQuery function, and it makes prototypical inheritance possible where you might need to apply the parent constructor on the child instance:

function MyJQuery(selector, context) {
    this.init(selector, context, MyJQuery.root); // <==
    // or more explicit:
    // jQuery.fn.init.call(this, selector, …);
    …
}
MyJQuery.fn = MyJQuery.prototype = Object.create(jQuery.fn);
MyJQuery.root = jQuery(document);
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Awesome, makes sense that the authors would do this since it sort of follows the `init` naming convention of [Resig's inheritance pattern](http://ejohn.org/blog/simple-javascript-inheritance/). – kavun Nov 03 '13 at 23:12
  • Exactly, only that Resig's pattern does not follow the JavaScript naming conventions which expect the initialisation method on the `.constructor` property :-) – Bergi Nov 03 '13 at 23:29