Analysis of the difference between two ways of accessing objects in JS

  • 2021-08-09 06:45:47
  • OfStack

You can access the properties and methods of an object in the following two ways

1. Object name. Attribute name. Object name. Method name ()

2. Object name ["Attribute name"] Object name "Method name"


   var obj = {
         name : " Xiao Ming ",
         age : 18,
         say : function(){
           console.log(" I am "+this.name+" I "+this.age+" Years old ");
         }      
     };
     console.log(obj.name);
     console.log(obj["name"]);
     obj.say();
     obj["say"]();

For existing properties and methods, use. and the result 1 obtained by [].

For nonexistent (undefined) properties and methods, using. creates the new property or method, while accessing using [] does not create the new property or method

For example, when traversing objects with for-in


    for(var x in obj){      
      console.log(x);    // Output obj The property name and method name in the 
      console.log(obj.x);// Want to use . The method of outputs the corresponding properties and methods    The result is undefined The reason is that JS In language . Method can be used to declare, and the way to declare an object property is the property name . Attribute value 
                           // It is actually stated here first obj Adj. x Property, and the property is not initialized, and then the property value is output, so it is undefined
       }

Using [] mode can only be accessed and read, and no new attributes will be defined


for(var x in obj){      
      console.log(x);    // Output obj The property name and method name in the 
      console.log(obj[x]);// Output the corresponding property value and method, the method is not called, so the output is the code of the method 
    }

Related articles: