简体   繁体   中英

JavaScript: Using same name for class/function and object?

I've looked here and basically (as far as I can tell) you can't use the same name for a function and an object, but looking at the following code, this does not seem to be the case. Can anyone tell me how this works?

;(function($){
    $.fn.superfish = function(op){

        var sf = $.fn.superfish,
            c = sf.c,
            $arrow = $(['<span class="',c.arrowClass,'"> &#187;</span>'].join('')),
...         
    };

    var sf = $.fn.superfish;
...
    sf.c = {
        bcClass     : 'sf-breadcrumb',
        menuClass   : 'sf-js-enabled',
        anchorClass : 'sf-with-ul',
        arrowClass  : 'sf-sub-indicator',
        shadowClass : 'sf-shadow'
    };  
...
})(jQuery);

And superfish has a reference to itself within its declaration. Would this not cause infinite recursion?

It is not recursion since it is not calling itself. It is referencing the properties off of the object.

If you saw something like this:

var sf = $.fn.superfish(),

than there would be an issue. :)

This is a common technique that allows you to store a reference to some deeply nested property and use that instead, for readability and performance. Crockford's article is related.

// some really deeply nested property
var o = ooo.eee.oo.ah_ah.ting.tang.walla.walla;

// i could type...
ooo.eee.oo.ah_ah.ting.tang.walla.walla.bing = true;

// or just
o.bing = true;

It just happens that, in this case, the deeply nested property is the object itself, but javascript does not care.

This fiddle demonstrates the exact javascript feature you're having trouble with. That's just the way javascript works. Not that I'd embrace this feature as a paradigm foundation, but it's possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM