Home > Web Front-end > JS Tutorial > What is jQuery.fn and How Does It Work?

What is jQuery.fn and How Does It Work?

DDD
Release: 2024-11-05 03:57:02
Original
380 people have browsed it

What is jQuery.fn and How Does It Work?

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template