JavaScript_ Notes 8 Object Object
Create Object instance
new operator + Object constructor
E.g:
var person = new Object(); // new 操作符,Object构造函数
person.name = 'Ahua'; // 添加name属性,并赋值
person.age = 21; // 添加age属性,并赋值
Object literal
Use object literals to create an object instance in the above example, such as:
var person = {
name : "Ahua',
age : 21
}
An object is created with two attributes, name and age, and corresponding values. This object is stored in the variable person.
The last attribute can not be added with a comma, it will be wrong in IE7 or earlier and Opera; the
object literal is more recommended because it has a small amount of code and can give people a feeling of encapsulating data.
Square bracket notation to access object properties
Put the accessed attributes in square brackets in the form of strings, such as:
alert(person["name"]); //访问person的name属性
The main advantage of square bracket notation-access object properties through variables
The main advantage of square bracket notation-access to object properties through variables, such as:
var propertyName = "name";
alert(person[propertyName]);
alert(person["name"]);
//如果属性名包含导致语法错误的字符,或属性名使用的关键字或保留字
//也可以采用方括号表示法
alert(person["first name"]);
Unless you must use variables to access attributes, dot notation is recommended