JavaScript object
An object is a collection of related data and methods (usually composed of some variables and functions, which we call attributes and methods in an object)
1. Object creation
Literal mode
var obj = { name:'TTTony', age:21, sayName:function(){ console.log(this.name); } }
Constructor Pattern
var obj = new Object(); obj.name = 'TTTony'; obj.age = 21; obj.sayName = function(){ console.log(this.name); }
2. Access to objects
- Property access
Point access method, bracket access method
obj.name // TTTony obj['name'] //TTTony
- Method access
Method access is mainly to execute the methods in the object, which needs to be used in the way of function call
//The execution result of the following code is different obj.sayName; obj.sayName(); // Use of methods
- Traversing properties in an object
for... in is used to traverse the properties of an array or object
for(var key in obj){ var value = obj[key]; }
The user-defined variable name key can be the element index of the array or the attribute of the object.
3. Add or delete attributes in objects
delete obj.pro; // Delete an attribute from an object obj.newproname = 'value'; // Add properties in object
4.Object display type conversion (forced type conversion)
- Boolean(value): converts the given value to boolean type
- String(value): converts the given value into a string
- Number(value): converts a given value into a number (which can be an integer or floating point number)
- Object type to Boolean type
var obj = { name:'TTTony', age:21 }; //Use the Boolean() wrapper for conversion console.log(Boolean(obj));
- Object type conversion String type
var obj = { name:'TTTony', age:21, // Rewrite the toString method to perform the transformation we want toString:function(){ return this.name +"-"+ this.age; } }; console.log(obj.toString(), typeof obj.toString()); console.log(String(obj), typeof String(obj));
Conversion rules:
1) Call the toString method of the object first
2) Judge whether the return value of this method is the basic data type (five basic data types)
3) If the return value is the basic data type, the conversion rules will convert it according to the conversion rules of the corresponding data type
4) If the return value is not the basic data type, continue to call the valueOf method based on the return value
5) Judge whether the return value of valueOf is the basic data type
6) Judge whether it is a basic data type. If it is a basic data type, operate 3
7) if it is still not the basic data type, an error will be reported
- Object type conversion Number type
var obj = { name:'TTTony', age:21, // 1. If only the valueOf() or toString() method is overridden, call the method and convert the return value with Number(). // 2. If both methods are overridden, call valueOf() and convert the return value with Number(). // 3. If both methods are not overridden, NaN is returned toString:function(){ return "100"; }, valueOf:function(){ return 10; } }; console.log(Number(obj));
Conversion rules:
1) Call the valueOf method of the object first
2) Judge whether the return value of the method is the basic data type (Number, String, Boolean, Undefined, Null)
3) If the return value is the basic data type, the conversion rules will convert it according to the conversion rules of the corresponding data type
4) If the return value is not the basic data type, continue to call the toString method based on the return value
5) Judge whether the return value of toString is the basic data type
6) Judge whether it is a basic data type. If it is a basic data type, operate 3
7) If it is still not the basic data type, an error will be reported
5. Attribute detection
Check whether a property belongs to an object:
in
Detect whether the property is a self owned or inherited property of an object
console.log("age" in obj); //If it exists, return true
Object.prototype.hasOwnProperty()
Check whether it is a self owned property, and the inherited property returns false
var obj = { name:'TTTony', age:21, school:'Stay at home and go to college' } console.log(obj.hasOwnProperty('name')); //true console.log(obj.hasOwnProperty('toString')); //false,toString is the inheritance property console.log(obj.hasOwnProperty('gender')); //false, there is no gender attribute in the object
Object.prototype.propertyIsEnumerable()
Check whether the attribute is self owned and created by us (enumerable)
var obj = { name:'TTTony', age:21, school:'Stay at home and go to college' } console.log(obj.propertyIsEnumerable('name')); //true console.log(obj.propertyIsEnumerable('toString')); //false,toString cannot be enumerated console.log(obj.propertyIsEnumerable('gender')); //false, there is no gender attribute in the object
6.Object prototype properties and methods
The properties and methods in the prototype Object of the Object constructor can be inherited by the instance of the Object constructor
Each constructor has a prototype object. The prototype object contains a pointer to the constructor, and the instance contains an internal pointer to the prototype object---- JavaScript advanced programming
Common methods in Object prototype
1) constructor saves the function that the user creates the current object
2) hasOwnProperty(proName) checks whether the property name is the object's own property
3) propertyIsEnumerable(proName) checks whether the given property exists in the current object instance
4) valueOf() returns string, numeric value, Boolean
5) toString() returns the string representation of the object
6) isPropertyOf() a.isPropertyOf(b) returns true if a is the prototype of B; If B is not an object or a is not the prototype of B, false is returned
7. In depth understanding of objects - defining attributes
ECMAScript has two attributes: data attribute and accessor attribute.
These two properties are used to set the advanced properties of the property, such as whether the property can be configured, read and write, traverse, and monitor data changes through setters and getters.
Data attribute properties
- [[Configurable]]: indicates whether to delete the attribute through delete to redefine the attribute, whether to modify the attributes of the attribute, or whether to modify the attribute as an accessor attribute. When it is false, it cannot be redefined and cannot be deleted using delete
- [[Enumerable]]: indicates whether the attribute can be returned through the for in loop
- [[Writable]]: indicates whether the value of the attribute can be modified
- [[Value]]: contains the data Value of this property
Modify the default properties:
Object. Defineproperty (object obj where the property is located, property name prop, a descriptor object descriptor)
Object.defineProperty(obj, 'name', { configurable:true, enumerable:true, writable:true, value:'TTTony' }) console.log(obj.name); Object.defineProperty(obj,'name',{enumerable:false}); //Modify the properties of the default attribute obj.propertyIsEnumerable("name"); //false
Modify the properties of multiple default attributes:
Object.defineProperty(obj, props)
var obj = new Object(); Object.defineProperties(obj, { name: { value: 'TTTony', configurable: false, writable: true, enumerable: true }, age: { value: 21, configurable: true } }) console.log(obj.name, obj.age) // zhangsan, 18
Read properties of attributes
Object.getOwnPropertyDescriptor(obj, prop)
Returns the property descriptor of a self owned property on the specified object
var person = { name: 'TTTony', age: 21 } var desc = Object.getOwnPropertyDescriptor(person, 'name'); console.log(desc); // { // configurable: true, // enumerable: true, // writable: true, // value: "TTTony" // }
Object.getOwnPropertyDescriptors(obj)
Returns the attribute descriptors of all self attributes of the specified object. If there is no self attribute, it returns an empty object
var obj = { name:'tony', age:21 }; var desc = Object.getOwnPropertyDescriptors(obj); console.log(desc); //{ // name: { // value: 'tony', // writable: true, // enumerable: true, // configurable: true // }, // age: { value: 21, writable: true, enumerable: true, configurable: true } //}
Accessor properties
This property does not contain data values. It contains a pair of get and set methods. When reading and writing accessor properties, these two methods are used for operation and processing
- [[Configurable]]: indicates whether to delete the attribute through delete to redefine the attribute, and whether to modify the attribute. The default is false
- [[Enumerable]]: indicates whether the attribute can be returned through the for in loop. The default is false
- [[Get]]: the function called when reading the property. The default value is undefined
- [[Set]]: the function called when writing the property. The default value is undefined
/** * Accessor properties: accessor properties do not contain values, but a pair of getter and setter functions; * The accessor property cannot be defined directly like the data property. It must be defined using the Object.defineProperty() method */ var obj = { _name:'tony', //The underscore indicates that it is an internal attribute and can only be read and written through the method of the object age:21 }; Object.defineProperty(obj, 'name', { get:function(){ return this._name; }, // If you only specify the get method and do not specify the set method, the property is read-only by default set:function(newName){ if(newName !== this._name){ this._name = newName; this.age++; } } }); // get and set methods in the test accessor console.log("Unmodified name:" + obj.name); obj.name = 'zhu'; console.log('Modified name: ' + obj.name); console.log('modify name Later age: ' + obj.age); // The questioner property can be queried through Object.getOwnPropertyDescriptor() console.log(Object.getOwnPropertyDescriptor(obj,'_name'));
8. Object serialization
Object serialization refers to converting the state of an object into a string.
You can also deserialize and restore the string to an object function.
JSON.stringify(obj) serializes objects into JSON strings. Only enumerable properties of objects can be serialized
JSON.parse(jsonStr) deserialization
var obj = { name:'tony', age:21 } console.log(obj); // Print out the object {name:'tony', age:21} // Convert object to string var json = JSON.stringify(obj); console.log(json); // Print out the string {name:"tony", age:21} console.log(JSON.parse(json)); //Print after converting string to object