Which way is best for creating an object in JavaScript? Is `var` necessary before an object property?

前端 未结 8 1870
无人共我
无人共我 2020-11-27 08:59

So far I saw three ways for creating an object in JavaScript. Which way is best for creating an object and why?

I also saw that in all of these examples the keyword

8条回答
  •  离开以前
    2020-11-27 09:23

    Of course there is a best way.Objects in javascript have enumerable and nonenumerable properties.

    var empty = {};
    console.log(empty.toString);
    // . function toString(){...}
    console.log(empty.toString());
    // . [object Object]
    

    In the example above you can see that an empty object actually has properties.

    Ok first let's see which is the best way:

    var new_object = Object.create(null)
    
    new_object.name = 'Roland'
    new_object.last_name = 'Doda'
    //etc
    
    console.log("toString" in new_object) //=> false
    

    In the example above the log will output false.

    Now let's see why the other object creation ways are incorrect.

    //Object constructor
    var object = new Object();
    
    console.log("toString" in object); //=> true
    
    //Literal constructor
    var person = { 
      name : "Anand",
      getName : function (){
       return this.name
      } 
    } 
    
    console.log("toString" in person); //=> true
    
    //function Constructor
    function Person(name){
      this.name = name
      this.getName = function(){
        return this.name
      } 
    }
    
    var person = new Person ('landi')
    
    console.log("toString" in person); //=> true
    
    //Prototype
    function Person(){};
    
    Person.prototype.name = "Anand";
    
    console.log("toString" in person); //=> true
    
    //Function/Prototype combination
    function Person2(name){
      this.name = name;
    } 
    
    Person2.prototype.getName = function(){
      return this.name
    }
    
    var person2 = new Person2('Roland')
    
    console.log("toString" in person2) //=> true
    

    As you can see above,all examples log true.Which means if you have a case that you have a for in loop to see if the object has a property will lead you to wrong results probably.

    Note that the best way it is not easy.You have to define all properties of object line by line.The other ways are more easier and will have less code to create an object but you have to be aware in some cases. I always use the "other ways" by the way and one solution to above warning if you don't use the best way is:

     for (var property in new_object) {
      if (new_object.hasOwnProperty(property)) {
        // ... this is an own property
      }
     }
    

提交回复
热议问题