jQuery.fn: Prototype Aliasing in jQuery
In jQuery, the term "fn" encountered in jQuery.fn.jquery refers to an alias for the prototype property of the jQuery constructor function ($). To comprehend this, it is crucial to grasp the concept of constructor functions in JavaScript.
A constructor function is used to create instances of objects, each of which inherits properties and methods from the constructor's prototype. In jQuery's case, the $ identifier serves as the constructor function.
For instance, consider the following constructor function:
<code class="javascript">function Test() { this.a = 'a'; } Test.prototype.b = 'b'; var test = new Test(); test.a; // "a", own property test.b; // "b", inherited property</code>
The Test constructor function creates an instance test that inherits from its prototype. The test instance has its own property a, while b is inherited from the prototype.
Similarly, jQuery follows a similar approach:
<code class="javascript">(function() { var foo = function(arg) { // core constructor // ensure to use the `new` operator if (!(this instanceof foo)) return new foo(arg); // store an argument for this example this.myArg = arg; //.. }; // create `fn` alias to `prototype` property foo.fn = foo.prototype = { init: function () {/*...*/} //... }; // expose the library window.foo = foo; })(); // Extension: foo.fn.myPlugin = function () { alert(this.myArg); return this; // return `this` for chainability }; foo("bar").myPlugin(); // alerts "bar"</code>
Here, the fn alias points to the prototype of the foo constructor function. Extending the fn property allows for adding new methods (such as myPlugin in the example) to all instances of the foo constructor.
The above is the detailed content of What is jQuery.fn and How Does It Work?. For more information, please follow other related articles on the PHP Chinese website!