Cleanest format for writing javascript objects

前端 未结 4 513
面向向阳花
面向向阳花 2021-02-06 19:20

What is the cleanest format for writing javascript objects?

Currently I write mine in the following format

if (Namespace1 == null) var Namespace1 = {};
i         


        
4条回答
  •  情歌与酒
    2021-02-06 20:06

    The module pattern may help you out here:

     var Namespace1 = Namespace1 || {};
        Namespace1.Namespace2 = Namespace1.Namespace2 || {};
    
        Namespace1.Namespace2.Class1 = function(param1, param2) {
            // define private instance variables and their getters and setters
            var privateParam = param1;
            this.getPrivateParam = function() { return privateParam; }
            this.publicParam1 = param2;
    
            return {
                init: function() {
                    alert('hi from Class1');
                }
            }
        } ();
    

    You can read more about it here: http://yuiblog.com/blog/2007/06/12/module-pattern/

        Namespace1.Namespace2.Class1.init();
    

提交回复
热议问题