As an example, copied from jQuery 1.2.6:
jQuery.fn = jQuery.prototype = {
init: function( selector, context ) {
// Make sure that a selection was provided
selector = selector || document;
..........
},
};
I have read some posts here like JavaScript: What are .extend and .prototype used for? and know a prototype can be used in a subclass to extend some methods.
But I cannot understand the usage in the above snippet from jQuery.
Are there any canonical documents describing the prototype?
Thanks.
All objects have a
prototypeproperty. It is simply an object from which other objects can inherit properties. The snippet you have posted simply assigns an object with some properties (such asinit) to theprototypeofjQuery, and aliasesjQuery.prototypetojQuery.fnbecausefnis shorter and quicker to type. If you forget about jQuery temporarily, consider this simple example:In this example,
Personis a constructor function. It can be instantiated by calling it with thenewoperator. Inside the constructor, thethiskeyword refers to the instance, so every instance has its ownnameproperty.The
prototypeofPersonis shared between all instances. So all instances ofPersonhave asayHellomethod that they inherit fromPerson.prototype. By defining thesayHellomethod as a property ofPerson.prototypewe are saving memory. We could just as easily give every instance ofPersonits own copy of the method (by assigning it tothis.sayHelloinside the constructor), but that’s not as efficient.In jQuery, when you call the
$method, you’re really creating an instance ofjQuery.prototype.init(remember thatjQuery.fn === jQuery.prototype):And if you look at
jQuery.fn.init:So really, you’re creating an instance of
jQuerywhich has access to all the methods declared onjQuery.prototype. As discussed previously, this is much more efficient than declaring those methods on each instance ofjQuery.