Cleanest format for writing javascript objects

前端 未结 4 552
面向向阳花
面向向阳花 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:16

    First of all, if you don't know if Namespace1 is defined, use typeof this.Namespace1 !== "undefined", as accessing Namespace1 will throw an error if it's not defined. Also, undefined properties are undefined, not null (though undefined == null). Your check will fail if something is actually null. If you don't want to use typeof for checking if properties are undefined, use myObject.property === undefined.

    Also, your second example has invalid syntax. Here is what I think you wanted to do:

    Namespace1.Namespace2.Class1.prototype = {
         publicParam1    : null,
         publicFunction1 : function () {/* Function body*/}
    };
    

提交回复
热议问题