2

Ive been using this way of defining a namespace

(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 ));

Now Id like to extend skillet to a sub namespace, like skillet.module and let module behave in the same way as skillet - protect its undefined, and allow private and public members.

Ive tried the other way of defining a namespace, inside skillet, do skillet.theObject = { blah: function() {} }; and so on but that only gives me a normal object and not private and public members in it.

4

1 回答 1

3

只需在函数中添加另一个立即调用的函数表达式,并将赋值参数传递给它,以便对其进行初始化。

(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);
    };

    (function (module) {
        module.test = function () { // access this by typing skillet.module1.test()
            if (isHot !== undefined) console.log(pour('water') + (isHot ? ', cold!' : ', hot!'));
        }

        function pour(what) {
            return 'Pouring ' + what;
        }
    )(skillet.module1 || (skillet.module1 = {})); // no need for undefined and $ rewriting as already done in parent function


    //Private Method
    function addItem(item) {
        if (item !== undefined) console.log("Adding " + $.trim(item));
    }    
}(window.skillet || (window.skillet = {}), jQuery));
于 2013-05-22T12:15:27.150 回答