Вопрос

I was reading How Good C# Habits can Encourage Bad JavaScript Habits article about creating namespace and modular pattern but I don't understand the reason to use $ and jQuery to create the namespace. Look at this code:

(function( skillet, $, undefined ) {
    //Private Property
    var isHot = true;

    //Public Property
    skillet.ingredient = "Bacon Strips";

    //Public Method
    skillet.fry = function() {
        var oliveOil;

        addItem( "\t\n Butter \n\t" );
        addItem( oliveOil );
        console.log( "Frying " + skillet.ingredient );
    };

    //Private Method
    function addItem( item ) {
        if ( item !== undefined ) {
            console.log( "Adding " + $.trim(item) );
        }
    }    
}( window.skillet = window.skillet || {}, jQuery ));

Why is it sending $ as parameter and then calling it with jQuery?

Это было полезно?

Решение

When you load the jQuery library, it binds two global symbols to a reference to the main function: "jQuery" and "$". Some other libraries also want to use "$", however, so jQuery provides a way to unbind "$" and restore it to whatever it was prior to loading jQuery. By using the technique in your example, you can use "$" in the code whether or not the global "$" refers to jQuery.

edit — that very article you referenced explains it similarly:

The second argument passed [is] jQuery. The benefit of this is that the named parameter is referenced as $, which allows us to refer to jQuery as $ within the Anonymous Function without having to worry that it will conflict with the $ declared in other JavaScript libraries. This is a common practice that you will most likely run across when looking at well written jQuery code.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top