Details of how to access JavaScript class properties

  • 2020-03-30 01:40:51
  • OfStack

How JavaScript class properties are accessed
 
var fish = { 
head : 1, 
tail : 1, 
feature : { 
speak : false, 
swim : true 
} 
} 

First, the dot operator:
 
console.log(fish.head);//1 
console.log(fish.tail);//1 
console.log(fish.feature);//Object { head:1, tail:1, feature: Object} 

Second, the [] operator:
 
console.log(fish['head']);//1 

One thing to note here is that the property name must be a string
Such as:
 
console.log(fish[head]);//Error!

So, is the following code correct?
 
for(var prop in fish) { 
console.log(fish[prop]); 
} 

The answer is yes, this is because the property of the object is traversed in a string type, that is, prop is 'head','tail','feature'.

Related articles: