What does prototype mean here in the jQuery source code?

后端 未结 1 1801
小蘑菇
小蘑菇 2020-12-12 14:24

As an example, copied from jQuery 1.2.6:

jQuery.fn = jQuery.prototype = {
    init: function( selector, context ) {
        // Make sure that a selection was         


        
相关标签:
1条回答
  • 2020-12-12 15:12

    All objects have a prototype property. 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 as init) to the prototype of jQuery, and aliases jQuery.prototype to jQuery.fn because fn is shorter and quicker to type. If you forget about jQuery temporarily, consider this simple example:

    function Person(name) {
        this.name = name;
    }
    Person.prototype.sayHello = function () {
        alert(this.name + " says hello");
    };
    
    var james = new Person("James");
    james.sayHello(); // Alerts "James says hello"
    

    In this example, Person is a constructor function. It can be instantiated by calling it with the new operator. Inside the constructor, the this keyword refers to the instance, so every instance has its own name property.

    The prototype of Person is shared between all instances. So all instances of Person have a sayHello method that they inherit from Person.prototype. By defining the sayHello method as a property of Person.prototype we are saving memory. We could just as easily give every instance of Person its own copy of the method (by assigning it to this.sayHello inside the constructor), but that's not as efficient.

    In jQuery, when you call the $ method, you're really creating an instance of jQuery.prototype.init (remember that jQuery.fn === jQuery.prototype):

    return new jQuery.fn.init(selector, context, rootjQuery);
    

    And if you look at jQuery.fn.init:

    jQuery.fn.init.prototype = jQuery.fn;
    

    So really, you're creating an instance of jQuery which has access to all the methods declared on jQuery.prototype. As discussed previously, this is much more efficient than declaring those methods on each instance of jQuery.

    0 讨论(0)
提交回复
热议问题