1

I got two questions about following code snippet.

(1). What is the purpose of "return new jQuery.fn.init( selector, context, rootjQuery );"? Why does it return another instance inside the JQuery function?

(2). Why prototype.constructor is re-defined as JQuery?

// Define a local copy of jQuery
var jQuery = function( selector, context ) {
 // The jQuery object is actually just the init constructor 'enhanced'
 return new jQuery.fn.init( selector, context, rootjQuery );
 },
... ...
jQuery.fn = jQuery.prototype = {
 constructor: jQuery,
 init: function( selector, context, rootjQuery ) {
 var match, elem, ret, doc;

Thank you!

asked Oct 4, 2011 at 6:50

2 Answers 2

4
  1. When JQuery is called as an ordinary function, a new (class) instance of JQuery is created and returned using new JQuery.fn.init(...). In this way, developers don't have to add the new keyword before $(..).
  2. JQuery.fn is a shortcut for JQuery.prototype. Writing JQuery.fn.customMethod = function(){...} is more convenient than writing JQuery.prototype.customMethod = .... Because JQuery is often also accessible through $ or $j, The shortesy way to refer to JQuery.prototype is $.fn.
James Montagne
78.9k14 gold badges115 silver badges132 bronze badges
answered Oct 4, 2011 at 6:56
Sign up to request clarification or add additional context in comments.

2 Comments

Hi Rob, what is "rootjQuery" parameter for? Thanks.
rootQuery is an internal parameter to refer to the JQuery-wrapped root of the document.
1

(2). Why prototype.constructor is re-defined as JQuery?

I think the reason is to keep a constructor reference inside each jQuery object, to actually itself (it creates a circular reference). In fact, by overriding the jQuery.prototype object with this piece of code

jQuery.fn = jQuery.prototype = { ... }

you lose the "automatically created" constructor (which points to the function it has been created from, in this case jQuery.fn.init), so you need to explicitly set it.

I've found this link very helpful to understand javascript prototype and contructor:

http://joost.zeekat.nl/constructors-considered-mildly-confusing.html

xpda
15.9k8 gold badges54 silver badges83 bronze badges
answered Jan 13, 2013 at 16:41

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.