How does jQuery have the $ object constructor and the methods associated with the $?

后端 未结 4 1581
你的背包
你的背包 2021-02-01 09:54

How is it that jQuery can do $(\"#foo\").addClass(\"bar\") and $.ajax()?

I\'m creating a micro javascript framework and want to create a new in

4条回答
  •  北恋
    北恋 (楼主)
    2021-02-01 10:29

    You can imitate the magic jQuery behaviour as following:

    //define
    var _$ = {};
    var $ = function(selector) {
               _$.html = function(args) {
                        alert("Doing the method 'html' with arguments " + args 
                               + " for selector " + selector);
                        return _$; //needed for pipeline
            };
            return _$; 
    };
    
    $.ajax = function(args){alert("Doing the method 'ajax' "); }
    
    //and try
    $("selector1").html("args1").html("args2");
    $.ajax("args2");
    

提交回复
热议问题