Cleanest format for writing javascript objects

前端 未结 4 557
面向向阳花
面向向阳花 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条回答
  •  Happy的楠姐
    2021-02-06 20:01

    Certainly rewrite the first two lines to this:

    var Namespace1 = Namespace1 || {};
    Namespace1.Namespace2 = Namespace1.Namespace2 || {};
    

    The rest of the looks ok. The private variable is pretty much how everyone does it. Static methods should be assigned to the prototype, as you have done.

    Do take care redefining the entire prototype for an object though, since it will prevent you from a common pattern of prototype-based inheritance. For instance:

    // You inherit like this...
    Sub.prototype = new Super();
    obj = new Sub();
    
    // Then you overwrite Sub.prototype when you do this:
    Sub.prototype = {foo:1, bar:2}
    
    // Instead, you should assign properties to the prototype individually:
    Sub.prototype.foo = 1;
    Sub.prototype.bar = 2;
    

提交回复
热议问题