开发者

Javascript Function like Objects i.e. "$" can be used as a function e.g. $() as well as an object $

开发者 https://www.devze.com 2023-01-01 15:40 出处:网络
Questions in the title. I\'ve always wondered and failed to find out from the jQuery source. How this is done.

Questions in the title. I've always wondered and failed to find out from the jQuery source. How this is done.

To reiterate. In jQuery: how does the "$" become a function e.g."$()" as well as an object "$."

I can create it one way OR the other like so...

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


var $ = {
    each:function(){console.log("Word")}
}
$.each(); // Word
//$().each(开发者_如何学Go); FAIL!


Start with the basic function:

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

Then, add extra functionality to it:

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

$.each = function()
{
    console.log("Called $.each()");
};

You can see how this pattern is used in jQuery by looking at 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
    }
}


in javascript a function is an object. you can create a function with properties, other functions (methods). just write this up in Javascript and look at the type of myfunc

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

when you look at the type of myfunc in Firebug you will see that the myfunc is an object.

0

精彩评论

暂无评论...
验证码 换一张
取 消