How does jQuery achieve making $ an alias for the jQuery function?

后端 未结 4 2170
一生所求
一生所求 2020-12-14 09:00

I’m having a little trouble wrapping my head around the $ sign being an alias for the jQuery function, particularly in a plugin. Can you explain how jQuery achieves this ali

4条回答
  •  星月不相逢
    2020-12-14 09:32

    Objects in JavaScript, and thus jQuery, are functions. You could define your own JS library by creating a function with other functions assigned to attributes of this single function:

    myLibrary = function() {
        this.myLibraryFunction = function() {
            ...
        };
    };
    
    new myLibrary().myLibraryFunction();
    

    In a similar way jQuery does this with a function named jQuery, instead of myLibrary in the above example.

    Creating Aliases

    Creating aliases (or references) is possible because JavaScript allows references to functions to be passed around without having to actually call the function. For example:

    new myLibrary().myLibraryFunction();
    

    calls your library function, however omitting the parentheses allows you to deal with a reference to that function:

    var f = new myLibrary().myLibraryFunction;
    

    You can then call the references you have stored, rather than the original by putting the parentheses back:

    var f = new myLibrary().myLibraryFunction;
    f();
    

    In the same way jQuery can store a reference to the jQuery function in another variable named $:

    var $ = jQuery;
    

    You can see this concept used in the jQuery source code on github.

提交回复
热议问题