代码之家  ›  专栏  ›  技术社区  ›  Drew

与对象类似的javascript函数,即“$”可以用作函数,例如$()以及对象。$

  •  4
  • Drew  · 技术社区  · 15 年前

    标题中的问题。我一直想知道,但从jquery源代码中找不到答案。这是怎么做到的。

    重申。在jquery中:“$”如何成为函数,例如“$()”以及对象“$”。

    我可以用这种或那种方式来创造…

    var $ = function(){
        return {each:function(){console.log("Word")}}
    }
    // $.each(); FAIL!
    $().each(); // Word
    
    
    var $ = {
        each:function(){console.log("Word")}
    }
    $.each(); // Word
    //$().each(); FAIL!
    
    2 回复  |  直到 15 年前
        1
  •  9
  •   John Millikin    15 年前

    从基本功能开始:

    var $ = function(expr) { return $.select(expr); }
    

    然后,添加额外的功能:

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

    通过查看 the source :

    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
        }
    }
    
        2
  •  2
  •   Marcel Korpel    15 年前

    在javascript中,函数是一个对象。您可以创建具有属性的函数、其他函数(方法)。只需用javascript编写这个,并查看 myfunc

    var myfunc = function() {
     //do stuff
    }
    

    当你看到 米芬克 在Firebug中,你会看到 米芬克 是一个对象。