JavaScript Namespace Declaration

后端 未结 8 1926
既然无缘
既然无缘 2020-12-07 15:09

I created a javascript class as follow:

var MyClass = (function() {
   function myprivate(param) {
      console.log(param);
   }

   return {
      MyPublic         


        
8条回答
  •  孤街浪徒
    2020-12-07 15:26

    This is the design pattern I use which allows for nested namespaces as well as adding to the namespace later (even from a separate JS file) so you don't pollute the global namespace:

    Example: JsFiddle

    (function ($, MyObject, undefined) {    
        MyObject.publicFunction = function () {
            console.log("public");
        };
    
        var privateFunction = function () {
            console.log("private");
        };
    
        var privateNumber = 0;
        MyObject.getNumber = function () {
            this.publicFunction();
            privateFunction();
            privateNumber++;
            console.log(privateNumber);
        };
    
        // Nested namespace
        MyObject.nested = MyObject.nested || {};
        MyObject.nested.test = function (text) {
            console.log(text);
        };    
    }(jQuery, window.MyObject = window.MyObject || {}));
    
    // Try it
    MyObject.getNumber();
    MyObject.nested.test('Nested');
    

    Here is how to add to MyObject from another JavaScript file:

    (function ($, MyObject, undefined) {
        MyObject.newFunction = function () {
            console.log("Added");
        };
    }(jQuery, window.MyObject = window.MyObject || {})); 
    // Pass `jQuery` to prevent conflicts and `MyObject` so it can be added to, instead of overwritten
    

    This resource helped me learn all about the different JS design patterns: http://addyosmani.com/resources/essentialjsdesignpatterns/book/

提交回复
热议问题