To understand JavaScript objects, we can start from object creation, property operations, and object methods. To summarize, it includes the following modules:
1. Create an object
1.1 Direct Object Measurement
The direct quantity of an object is the easiest way to create an object, and it consists of several name/value pairs:
var point = {x: 0, y: 0 };There is no limit to attribute names. They can be js keywords or any strings. If these two situations, the attributes need to be enclosed in double quotes:
var empty = {};va point = {x: 0, y: 0 };var book = {"main title": "Javascript","sub-title": "The definitive Guide","for": "all audience",author: {firstName: "Davide",lastName: "Flanagan"}};It is very simple to create objects directly, but it is generally not used in this way. The code is low reusable. If you want to use the object elsewhere and the attribute values are different, then do this? Do you have to recreate another code?
1.2 Create an object through new
Before creating an object through new, you must first create a function, and new treats this function as a constructor. For example, create a Person object through new:
function Person(){//Constructor}var person = new Person();Primitive types in the core of the Javascript language all contain built-in constructors:
var a = new Array();var d = new Date();var r = new RegExp("js");1.3 Object.create()
Before we understand the create method of Object, we want to see what a prototype is. Each Javascript object (except null) is associated with another object. The "another" object is what we call a prototype. Each object inherits attributes from the prototype.
All objects created through object direct quantity have the same prototype object Object.prototype. The object prototype created by the keyword new and constructor is the value of the constructor's prototype property. The prototype of the object created through new Array() is Array.prototype, and the prototype of the object created through new Date() is Date.prototype. The prototype has been introduced here.
The Object.create method contains two parameters. The first parameter is the prototype of the object and the second parameter is optional to describe the object properties. It's easy to use, just pass in the required prototype object:
var o1 = Object.create({x: 1, y: 2 }); //The prototype is Object.prototypeIf you want to create an object without a prototype, you can pass null as a parameter. The objects created in this way do not inherit any properties, and there is no method like toString:
var o2 = Object.create(null); //No prototype
If you want to create a normal empty object, pass it directly into Object.prototype:
var o3 = Object.create(Object.prototype);
If it is a custom object, it is the same as creating an empty object. Pass the object name directly.prototype:
function Person(){}var o4 = Object.create(Person.prototype);2. Attribute management
2.1 Property query and settings
The properties of an object can be obtained through the dot (.) or square bracket ([]) operator. If you use dots to get the attribute, the attribute name must be a simple indicator. It cannot be a reserved word, such as o.for or o.class.
ar author = book.author; //Correct var name = author.surname; //Correct var title = book["main title"]; //Correct var className = book.class; //Error
The syntax of object["property"] looks more like an array, except that the elements of this array are indexed by strings rather than numbers. This kind of array is what we call an associative array, also known as hash, map or dictionary. Javascript objects are associative arrays.
Since the object is an associative array, Javascript also provides us with a method for/in to traverse properties. The following example uses for/in to calculate the total value of portfolio:
function getvalue(portfolio){ var total = 0.0; for(stock in portolio){ var shares = portolio[stock]; var price = getquote(stock); total += shares * price; } return total;}Inheritance: Javascript objects have their own properties, and some properties are inherited from prototype objects. Let's first look at a function inherit that implements inheritance:
function inherit(p){ if (p == null) throw TypeError(); //p is an object, it cannot be null if(Object.create){ return Object.create(p); //Use the Object.create method directly} var t = typeof p; if(t !== "object" && t !== "function") throw TypeError(); function f() {}; f.prototype = p; //Set its prototype attribute to p return new f();}Suppose you want to query the attribute x of object o. If x does not exist in o, you will continue to query the attribute x in the prototype object of o. If there is no x in the prototype object, but the prototype object also has a prototype, then continue to execute the query on the prototype object's prototype until x is found or a null object is found.
var o = {}; //oInherit object attribute ox = 1 from Object.prototype; //Define x attributes for o var p = inherit(o); //pInherit o and Object.prototypep.y = 2; //PDefine attribute yvar q = inherit(p); //qInherit p, o and Object.prototypeq.z = 3; //Define attribute zvar s = q.toString(); //toString inherits from Object.prototypeq.x + qy // => 3: x and y inherit from o and p respectively2.2 Delete attributes
The delete operator can delete the object's properties:
delete book.author;delete book["main title"];
delete can only delete its own attributes, and cannot delete inherited attributes. To delete an inherited property, it must be deleted from the prototype object that defines the property, and this affects all objects inherited from the prototype. Deletion will return true.
ar o = {x: 1};delete ox; //Delete x and return truedelete ox; //X no longer exists, nothing is done, return true. delete o.toString; //Do nothing, return true. delete cannot delete attributes with configurable type false. The properties of some built-in objects are not configurable, such as the properties of the global object created through variable declarations and function declarations: delete Object.prototype //It cannot be deleted, the properties are not configurable var x = 1;delete this.x; //This property cannot be deleted function f() {}delete this.f; //The global function cannot be deleted2.3 Detect properties
To determine whether a property exists in an object, it can be detected by the in operator, hasOwnProperty() and propertyIsEnumerable() methods.
in operator: The operator is the property name on the left and the object on the right. Return true if the object's own attribute or inherited attribute contains attributes:
var o = {x: 1};"x" in o; //true: x is the attribute "y" in o; //false: y is not the attribute "toString" in o; //true: o inherits the toString attributehasOwnProperty() method: detects whether the given name is the object's own property. For inherited attribute it will return false:
var o = {x: 1};o.hasOwnProperty("x"); //true: o has a free property xo.hasOwnProperty("y"); //false: no property yo.hasOenProperty("toString"); //false: toString is an inheritance propertypropertyIsEnumerable() method: is an enhanced version of hasOwnProperty. It will return true only if the own property is detected and this property is held as true:
var o = inherit({y: 2});ox = 1;o.propertyIsEnumerable("x"); //true: o has an enumerable property xo.propertyIsEnumerable("y"); //false: y is the inherited Object.prototype.propertyIsEnumerable("toString"); //false: Cannot be enumerable2.4 Enumeration properties
Usually, for/in is used to loop through object properties, and the traversed properties include their own properties and inherited properties. Built-in methods of object inheritance are not enumerable, but the properties added to objects in the code are enumerable. For example:
var o = {x: 1, y: 2, z: 3}; //Three enumerable properties o.propertyIsEnumeable("toString"); //false, cannot be enumerated for (p in o) //Transfer property console.log(p); //Output x, y and z, no toString outputSometimes we just want to iterate over our own properties, and the properties are not functions:
for(p in o){ if(!o.hasOwnProperty(p)) continue; if(typeof o[p] === "function") continue;}We can copy enumerable attributes through the enumeration traversal function:
/** Copy the enumerable attributes in p into o and return o* If o and p contain attributes of the same name, overwrite the attributes in o* This function does not handle getters and setters and copy attributes*/function extend(o, p){ for(prop in p){ //Transfer all attributes in p o[prop] = p[prop]; //Add attributes to o} return o;}ES5 defines two functions that enumerate attribute names. The first is Object.keys(), which returns an array composed of enumerable attribute names in the object. The second enumeration function is Object.getOwnPropertyNames(), which is similar to Object.keys(), which returns all the object's own properties, not just enumerable properties.
3. Attribute encapsulation
3.1 Attributes getter and setter
Object attributes are composed of names, values and a set of attributes. In ES5, attribute values can be replaced by one or two methods, which are getters and setters. The attributes defined by getters and setters are called "accessor attributes". Unlike "data attributes", the data attributes have only one simple value.
Unlike data attributes, the accessor attribute is not writeable. If the property has both getter and setter methods, then it is a read/write property. If it has only getter methods, then it is a read-only property, if it has only setter methods, then it is a write-only property. Reading write-only attributes always returns undefined.
The accessor attribute definition syntax is also relatively simple. Function definition does not use the function keyword, but uses get or set:
var o = { //Ordinary data attribute data_prop: 1, //Accessor attributes are all pairwise defined functions get accessor_prop(){/* Here is the function body*/}, set accessor_prop(value){}};Think about the following object that represents the coordinates of 2D Cartesian points. It has two normal properties x and y represent x coordinates and y coordinates respectively. It also has two equivalent accessor properties to represent the polar coordinates of points:
var p = { //x and y are ordinary read-write data attributes x: 1.0, y: 1.0, //r is a read-write accessor attribute, which has getter and setter get r(){return Math.sqrt(this.x * this.x + this.y * this.y); }, set r(newValue){ var oldValue = Math.sqrt(this.x * this.x + this.y * this); var ratio = newValue / oldValue; this.x *= ratio; this.y *= ratio; }, //theta is a read-only accessor attribute, only getter method get theta() { return Math.atan2(this.y, this.x); }};Like data attributes, the accessor attributes are inheritable, so the p object in the above code can be regarded as a prototype of another "point". It can define its x and y properties for a sexual object, but the r and theta properties inherit from:
var q = inherit(p);qx = 1, qy = 1;console.log(qr);cosole.log(q.theta);
3.2 Attribute Features
We can regard the getter and setter methods of the accessor attribute as attribute characteristics. According to this logic, we can also look at the properties' characteristics of the properties as well. Therefore, it can be considered that a property contains a name and 4 attributes.
The four characteristics of a numeric property are its value, writeable, enumerable and configurable.
Accessor attributes do not have value characteristics and writability, so they include: read (get), write (set), enumeration, and configurability.
ES5 defines an object named "Attribute Descriptor", which represents those 4 attributes. The attributes of the descriptor object of the data attribute include value, writable, enumerable and configurable. The descriptor object of the accessor attribute is replaced by the get attribute and the set attribute. Among them, writable, enumerable, and configurable are boolean values, and the get attribute and set attribute are function values.
You can get the property descriptor for a specific property of an object by calling Object.getOwnPropertyDescriptor():
//Return {value: 1, writable: true, enumerable: true, configurable: true}Object.getOwnProeprtyDescriptor({x: 1},"x");//Query the octet property of the random object defined above//Return {get: /*func */, set: undefined, enumerable: true, configurable: true}Object.getOwnPropertyDesciptor(random, "octet");//For inherited attributes and non-existent attributes, return undefinedObject.getOwnPropertyDesciptor({}, "x");Object.getOwnPropertyDesciptor({}, "toString");As you can see from the function name, Object.getOwnPropertyDesciptor() can only get the descriptor of its own properties. To obtain the characteristics of inherited attributes, you need to traverse the prototype chain (Object.getPrototypeOf()).
If you want to set the properties of the properties, or make the newly created properties have certain properties, you need to call Object.defineProperty(), which contains three parameters: object, property name, and property descriptor object:
// Properties exist, but ox cannot be enumerated; //=> 1Object.keys(o) //=> []//Now modify the property x to make it read-only Object.defineProperty(o, "x", {writable: true });//The view changes the value of this property ox = 2; //The operation fails but no errors are reported, and a type error exception is thrown in strict mode//Properties are still configurable, so it can be modified in this way: Object.defineProperty(o, "x", {value: 2 });ox //=> 2//Now modify x from the data property to the accessor property Object.defineProperty(o, "x", { get: function() { return 0;} });ox // => 0If you want to modify or create multiple properties at the same time, you need to use Object.defineProperties(). The first parameter is the object to be modified, and the second parameter is a mapping table. For example:
var p = Object.defineProperties({}, { x: { value: 1, writable: true, enumerable: true, configurable: true}, y: { value: 2, writable: true, enumerable: true, configurable: true}, r: { get: function(){ return Math.sqrt(this.x * this.x + this.y * this.y); }, enumerable: true, configurable: true }});Old-fashioned APIs for getters and setters: Before ES5, most Javascript implementations could already support get and set writing in object direct quantity syntax. These implementations provide non-standard old-fashioned APIs for querying and setting getters and setters. These APIs are composed of four methods, and all objects have these methods.
__lookupGetter__() and __lookupSetter__() are used to return a named attribute getter and setter method.
__defineGetter__() and __defineSetter__() are used to define getters and setters. The first parameter is the attribute name, and the second parameter is the getter and setter methods.
var o = {};o.__defineGetter__("x", function(){return 0;});o.__defineSetter__("y", function(value){console.log("set value:" + value);});4. Three properties of an object
Each object has a prototype, class, and extensible attribute related to it. Next, let’s talk about what these attributes do.
4.1 Prototype properties
The prototype attributes of an object are used to inherit attributes. We often call "o's prototype attributes" directly "o's prototype". Previously, "Create Objects" introduced three ways to create objects. Objects created by objects are used as their prototype using Object.prototype. Objects created by new use the constructor's prototype attribute as their prototype. Objects created with Object.create() use the first parameter as their prototype.
In ES5, the object prototype can be queried through Object.getPrototypeOf(). In ES3, there is no equivalent function, but instead the expression o.constructor.prototype is used to check the prototype of the object.
To detect whether an object is a prototype of another object (or is in the prototype chain), use the isPrototypeOf() method. For example, you can detect whether p is a prototype of o by p.isPrototypeOf(o):
var p = {x: 1}; //Define a prototype object var o = Object.create(p); //Use this prototype to create an object p.isPrototypeOf(o); //=> true,o inherits from pObject.prototype.isPrototypeOf(o) //=> true, p inherits from Object.prototypeJavascript implemented by Mozilla exposes an attribute specifically named __proto__ to directly query/set object prototype. However, IE and Opera do not support the __proto__ attribute, so it is not recommended to use the __proto__ attribute directly.
4.2 Class Attributes
An object's class attribute is a string to represent the object's type information. Both ES3 and ES5 provide methods to set this property, and there is only one indirect way to query it. The default toString() method returns a string in this format: [object class].
You can call the toString() method and then extract the characters between the eighth and the penultimate position of the returned string. But there is a problem that many objects inherited toString() methods have been rewritten. In order to be able to call the correct toString() version, the Function.call() method must be indirectly called. The classof function in the following example can return the class of any object:
function classof(o){ if(o === null) return "Null"; if(o === undefined) return "Undefined"; return Object.prototype.toString.call(o).slice(8, -1);}4.3 Scalability
The extensibility of the object is used to indicate whether new properties can be added to the object. All built-in and custom objects are explicitly extensible. In ES5, objects can be converted to non-scalable.
In addition to setting the object to be non-extensible, the Object.seal() method can also set all the object's own properties to be non-configurable. That is to say, new attributes cannot be added to the object, and existing attributes cannot be deleted and configured.
The Object.isSealed() method is used to detect whether the object is enclosed.
The Object.freeze() method will lock objects more strictly. In addition to having the function of the Object.seal() method, it can also set all its own data attributes to read-only (if the object's accessor attribute has a setter method, the accessor attribute is not affected, and you can still call them by assigning values to the attributes).
Object.isFrozen() is used to detect whether the object is frozen.
5. Serialize objects
Object serialization refers to converting the state of an object into a string, or you can restore the string to an object. ES5 provides built-in functions JSON.stringify() and JSON.parse() to serialize and restore Javascript objects. These methods all use JSON as the data exchange format. For example:
o = {x: 1, y: {z: [false, null, ""]}}; //Define a test object s = JSON.stringify(o); //{"x":1,"y":{"z":[false, null,""]}}p = JSON.parse(s); //p is a deep copy of oThe syntax of JSON is a subset of the Javascript syntax, and it cannot represent all values in Javascript. Objects, arrays, strings, infinite numbers, true, false, and null are supported, and they can be serialized and restored. NaN, Infinity and -Infinity serialization results are all null. Functions, RegExp, Error objects, and undefined values cannot be serialized and restored.
Here I will add the method of the object:
toString() method: It will return a string representing the value of the object that calls this method. Many objects have rewritten the toString() method, such as Array.toString(), Date.toString() and Function.toString().
toJSON() method: Object.prototype does not actually define the toJSON() method, but because of the need to perform serialization, the JSON.stringify() method will call the toJSON() method. If this method exists in the serialized object, it is called.
valueOf() method: The valueOf() method is very similar to the toString() method, but Javascript often calls it when it converts an object to a certain original value rather than a string, especially when it is converted to a number. Some built-in classes customize the valueOf() method, such as Date.valueOf().
The above article comprehensively understands the advancement of JavaScript objects is all the content I share with you. I hope it can give you a reference and I hope you can support Wulin.com more.