This article mainly introduces objects in JavaScript. This article describes how to create and delete objects using examples, and summarizes Object attributes and Property attributes, you can refer to JavaScript where all values except number, string, boolean, null, and undefined are objects. Objects can be directly declared by literal, or new objects can be created by using the new operator. Unlike Java, the property in a JavaScript object can be dynamically added or deleted. In addition, the property in the object can also be a null string:
The code is as follows:
// Properties in object can be added/deleted dynamically
Var o = {x: 1, y: 2 };
Console. log (o); // Object {x = 1, y = 2}
Delete o. y;
O. z = 3;
Console. log (o); // Object {x = 1, z = 3}
// Empty string is allowed as object property
Var o2 = {"": 88, "p": 99 };
Console. log (o2); // Object {= 88, p = 99}
// For constructor function, "new" operation returns an object.
Function Computer (x, y ){
This. x = x;
This. y = y;
}
Var c = new Computer (126,163 );
Console. log (c); // Computer {x = 126, y = 163}
Var c2 = new Computer (126); // missing parameter value will be "undefined"
Console. log (c2); // Computer {x = 126, y = undefined}
C. z = 66;
Console. log (c); // Computer {x = 126, y = 163, z = 66}
Delete c. y;
Console. log (c); // Computer {x = 126, z = 66}
If you use the new operator to create an object, the function is not a constructor of the class, but a common function, JavaScript will return an empty object after executing the function:
The code is as follows:
// For pure function, "new" operation returns an empty object.
Function compute (x ){
Console. log ("execute function compute ");
Return x * 2;
}
Var a = new compute ();
Console. log (a); // compute {}
Object attributes
Objects in JavaScript have the following three attributes:
1. prototype. Reference, pointing to the prototype Object of the Object. The property in the prototype Object can be inherited by the Object.
2. class. String, indicating the class name of the Object.
3. extensible. Boolean value, indicating whether to allow dynamic addition of property in the Object. This attribute is only valid in ECMAScript 5.
Property
The Property in the Object also has three attributes:
1. writable. Whether the property is writable.
2. enumerable. Whether the property is enumerated when the for/in statement is used.
3. retriable. Whether the property can be modified or deleted.