Javascript函数就像对象,即"$"可以用作函数,例如$()以及对象$

Dre*_*rew 4 javascript

标题中的问题.我一直想知道并且未能从jQuery源代码中找到答案.如何做到这一点.

重申一下.在jQuery中:"$"如何成为一个函数,例如"$()"以及一个对象"$".

我可以像这样或另一种方式创建它...

var $ = function(){
    return {each:function(){console.log("Word")}}
}
// $.each(); FAIL!
$().each(); // Word


var $ = {
    each:function(){console.log("Word")}
}
$.each(); // Word
//$().each(); FAIL!
Run Code Online (Sandbox Code Playgroud)

Joh*_*kin 9

从基本功能开始:

var $ = function(expr) { return $.select(expr); }
Run Code Online (Sandbox Code Playgroud)

然后,为其添加额外的功能:

$.select = function(expr)
{
    console.log("selecting " + expr);
    return $; // TODO: perform selection
};

$.each = function()
{
    console.log("Called $.each()");
};
Run Code Online (Sandbox Code Playgroud)

您可以通过查看源代码来了解如何在jQuery中使用此模式:

var jQuery = function( selector, context ) {
    // The jQuery object is actually just the init constructor 'enhanced'
    return new jQuery.fn.init( selector, context );
}

jQuery.fn = jQuery.prototype = {
    init: function( selector, context ) {
        var match, elem, ret, doc;

        // Handle $(""), $(null), or $(undefined)
        if ( !selector ) {
            return this;
        }

        // contents of init() here
    }
}
Run Code Online (Sandbox Code Playgroud)