Object attribute call of JavaScript relearning

For a JavaScript object:

var obj = {
    
    
	name: "Jack",
	age: 12,
	sayHello: function(){
    
    
		console.log("Hello!")
	}
}

There are two ways to call its properties

. transfer

The encoding of attribute names is simple and intuitive, easy to use

console.log(obj.name)
console.log(obj.age)
console.log(obj.sayHello)	//注意这里我没有加(),因此不算调用方法,只是输出函数

Insert picture description here

[]transfer

. Calls that can be completed, [] can also be completed

console.log(obj['name'])
console.log(obj['age'])
obj['sayHello']()	//注意这里我加了(),因此这里是在调用方法

Insert picture description here

You can only use [] instead of.

In JavaScript, in some cases, we can only use [] to call the properties of the object:

The attribute name contains special characters (-space)

When there are special characters in our property name, for example, we want to call a Content-Type property in the current object , then we use. Calling will cause a syntax error.
Just change to the [] method.

The attribute name is in the form of a variable

If our attribute name is now in the form of a variable, then we use two methods to set the attributes separately, and finally output to see what is different.

var obj = {
    
    }

var propName = "name"
obj.propName = "小李"
obj[propName] = "小张"

console.log(obj)

Insert picture description here
You can see that there are two properties, name and propName. As shown in the figure, the propName is treated as a property name, which is obviously not what we want, what we want is the first name property.
Therefore, if we want to access properties in the form of parameters, we can only use the [] method.

to sum up

If the. Method does not affect the function, the use of the. Method is of course what we want to see, except for two cases:

  1. Special characters in the attribute name
  2. The attribute name is in the form of a variable

Guess you like

Origin blog.csdn.net/qq_43592084/article/details/110304877