Sixth Chapter Object
An object can be considered an unordered collection of its properties, and each property is a name/value pair. JavaScript objects are dynamic, can be added or can be deleted, and can manipulate objects by reference, not by value. If the variable x is a reference to an object, execute the code var y=x, and the variable y will also point to the reference to the same object, not to the copy of the object, so modifying the object with the variable y will also have an effect on the X.
The most common uses of objects are creating (create), setting (set), finding (query), deleting (delete), detecting (test), and enumerating (enumerate) its properties.
Attributes include a name and a value. The property name can be any string that contains an empty string, and the value can be any value. In addition to the name and value, the attribute has some value associated with it, called the property attribute:
(1) Writable: Indicates whether the value of the property can be set.
(2) Enumerable: Indicates whether the property can be returned through a for/in loop.
(3) Configurable: Indicates whether the property can be deleted or modified.
First, create the object
1. Direct volume of objects
var empty={}; // var point={x:0,y:0}; var point2={x:point.x,y=point.y}; var book={ "main title": "JavaScript", // "Sub-tit": "The Definitive Guide", // for: ' All audiences ', // property named reserved word , you must use the quotation marks author:{FirstName: "David" , Surname: "Flanagan" }};
2. Create an object from new
A call implementation that follows a constructor after the keyword new.
var o=New Object (); // Create an empty object, as directly as the direct amount {} var a=New Array (); // create an empty array, as in [] var d=New Date (); // Create a Date object that represents the time of the moment var New REGEXP ("JS"); // Create a RegExp object that can be pattern-matched
3. Prototypes
Each JavaScript object is associated with another object, which is a prototype, and each object inherits properties from the prototype.
Second, the property of the query and settings
var author=book.author; // get the "author" property of Book var name=Author.surname; var title=book["main title"]; // get the "main title" property of Book
1. An object that is an associative array.
The following two JavaScript expressions have the same values:
object.propertyobject["property"]
The second syntax is more like an array, except that the index is a string, which is the meaning of the said associative array (associalive array), also known as a hash, map, or dictionary. JavaScript objects are associative arrays.
In strongly typed languages such as C, Java, objects can only have a fixed number of attributes, and these attribute names must be defined in advance. Because JavaScript is a weakly typed language, you do not have to follow these requirements, and any number of properties can be created by programs in any object.
In JavaScript, when a property is accessed through the dot operator (.), the property name is represented by an identifier (not a data type), so the program cannot modify the property name in this case. When you access the properties of an object by [], the property name is represented by a string, which is the data type, and you can modify or create the property name, as in the following code:
var addr= ""; // read the properties of the Costomer object Address0, Address1 // Address2, ADDRESS3; // and connect the values of each property together for (i=0;i<4;i++) { addr+=customer["address" +i]+ ' \ n ';}
This code can also be overridden by the dot operator, but many scenarios can only be done using array notation. Suppose a program uses network resources to calculate the current user's stock market investment. The program allows the user to enter the name and share of each stock. The program uses the Portfolio object to store this information, the property name is the stock name, and the attribute value is the purchase quantity. The following function is used to add a new stock to the Portfolio object:
function Addstock (portfolio,stockname,shares) { // This is obviously only used for array notation / / if " Portfolio.stockname " / / is to assign an attribute named" StockName "to the object / / The actual demand is not so portfolio[stockname]=shares;}
2. Inheritance
JavaScript objects have "own properties" (own property), and some properties are inherited from prototype objects.
If the object O's property x is queried, if X does not exist in O, the property X will continue to be queried in the prototype object of O, and if there is no X in the prototype property of O, it will continue to be found in the prototype object of the prototype object until it finds X or finds an object with the prototype null.
var o={}; // O method o.x=1 for inheriting objects from Object.prototype ; var p=inherit (o); // p inherit o and Object.prototypep.y=2; var q=inherit (p); // Q Inherits O/p/object.prototypeq.z=3; var s=q.tostring (); // The toString () method inherits from Object.prototypeq.x+q.y; // output 3
For the above code, if the property X of the object o is assigned a value, if the attribute x already exists, it is the value of the modification, if the property does not exist, then the assignment action will add a new attribute x to the object o.
The property assignment operation first checks the prototype chain to determine whether the assignment operation is allowed. For example, if O inherits from a read-only attribute x, then the assignment operation is not allowed, and the assignment operation does not affect the properties of the prototype object. In JavaScript, inheritance is only reflected when querying properties, and setting properties is irrelevant to inheritance.
var unitcircle={r:1}; // an object to inherit from var c=inherit (unitcircle); // c inherit unitcircleC.x=1;c.y=1; // set the attribute of C c.r=2; // overwrite the original inherited attribute UNITCIRCLE.R; // Output 1, the properties of the prototype object have not changed
Property assignment Either fails, creates a property, or sets a property in the original object, with one exception: if o inherits from Attribute X, and this property is a accessor property with setter methods, then this is the call setter method instead of creating an attribute X for O. It is important to note that the setter method is called by the object o, not the prototype object that defines the property, and this operation is only for the O itself and does not modify the prototype chain.
3. Property Access Error
When a non-existent property is queried, that is not found in either the object's own property or the inheritance property, the undefined is returned without an error. However, if the object itself does not exist, then an error will be found. In another case, null and undefined values do not have attributes, so querying the properties of these values will result in an error.
Third, delete attributes
Delete // Delete Book's author property Delete book["main title"]; // Delete book's "Main title" Property
The delete operator can only delete its own property, cannot delete the inherited property, and to delete the inherited property must be removed from the prototype object that defines the property, and this affects all objects that inherit the prototype.
Returns true if delete succeeds or does not have any side effects, and returns True (because there is no meaning) if the delete is not a property-access expression.
O={x:1}; delete o.x; // returns True delete o.x; // x is gone, meaningless operation, return True delete o.tostring; // Meaningless operation, ToString is inherited, returns True Delete 1; // Meaningless operation, return True
The delete operator cannot remove properties that are configurable as false, such as the properties of global objects created through variable declarations and function declarations.
delete object.prototype; // cannot be deleted, this property is not configurable var x=1; delete this . x; // cannot delete the global object's properties (global variables) function F () {} delete this . F; // cannot delete global function
// When you delete a configurable property of a global object in a non-strict mode // you can omit a reference to a global object by using the property name directly // declared with Var is not configurable this. x=1; // Create a configurable global property delete x; // Delete x // in strict mode, you must explicitly specify an object and its properties delete x; // syntax errors are reported in strict mode Delete this. x; // Normal work
Iv. Detection Properties
The
can be used by the in operator, the hasOwnProperty (), and the propertyIsEnumerable () method to determine whether a property exists in an object.
var o={x:1} "X" in o; // true "y" in o; // false "toString" in o; // true, inheritance property // hasownproperty () detects if the property is own property var o={x:1}o.hasownproperty ( "x"); // true o.hasownproperty ("Y"); // false o.hasownproperty ("toString"); // false
The propertyIsEnumerable () method returns true only if it detects that the property is its own property and the number is enumerable.
var o=inherit ({y:2}) o.x=1; o.propertyisenumerable ("x"); // trueo.propertyisenumerable ("Y"); // false Object.prototype.propertyIsEnumerable ("toString"); // false, non-enumerable
V. Enumeration properties
The for/in loop iterates through all the enumerable properties of an object in the loop, assigning the property name to the variable. The built-in methods for object inheritance are not enumerable, but the properties that are added to the object in code are enumerable.
var o={x:1,y:2,z:3} o.propertyisenumerable ("toString"); // false for inch o) Console.log (p); // output x, Y, Z. Not output tostring
//Object tool functions for enumerating properties/** Copy the enumerable attribute in P to O and return o * if O and P have the same name property, overwrite the property in O * This function does not handle getter and setter and copy properties*/functionExtend (o,p) { for(Proinchp) {O[pro]=p[pro];//To add an attribute to the O } returno;}/** Copy the enumerable attribute in P to O and return o * if O and P have the same name attribute, the property in O is not affected * This function does not handle getter and setter and copy properties*/functionMerge (o,p) { for(Propinchp) {if(O.hasownproperty[prop])Continue;//If there is a property with the same name, skipo[prop]=P[prop]; } returno;}/** If the property in O does not have the same name in P, the property in O is removed*/functionRestric (o,p) { for(Propinchp) {if(!o.hasownproperty (prop))//easy to use "! (Prop in O) Replace DeleteO[prop]; } returno;}/** If the property in O has the same name in P, the property in O is removed*/functionRestric (o,p) { for(Propinchp) {if(Propincho)DeleteO[prop]; } returno;}/*returns a new object that has both O and P properties * If there is a duplicate attribute in O and P, use the property in P*/functionUnion (O,P) {x={}; for(Propinchp) {if(Propincho) X[prop]=P[prop]; } returnx;}//a more concise notation.functionUnion1 (o,p) {returnRestric (Extend ({},o), p);}
Vi. attribute getter and setter
Properties defined by getter and setter are called accessor properties (accessor property), which differs from the Data property and has a simple value for the Data property. The Getter method is called when the program queries the value of the accessor property, and the setter method is called when the program sets the value of the accessor property.
The simplest way to define accessor properties is to use an extension of the object's direct amount syntax:
var o= { // Normal data attribute data_prop:value, // Accessor properties are all paired-defined functions get Accessor_prop () {/ * function Body Contents * / }, set Accessor_prop (value) { /* function Body Contents * / }}
Accessor properties are defined as one or two functions with the same name as the attribute, and it is important to note that the function definition does not use the Functions keyword, but rather uses get and set.
varp={ //x and Y are common, readable and writable data propertiesx:1.0, y:1.0, //R is a read-write accessor property //A comma is required after the function body endsget R () {returnMATH.SQRT ( This. x* This. x+ This. y* This. Y); }, set R (newvalue) {varOLDVALUE=MATH.SQRT ( This. x* This. x+ This. y* This. Y); varRatio=newvalue/oldvalue; This. x *=ratio; This. Y *=ratio; }, //Theta is a read-only accessor attribute, only the Getter methodGet Theta () {returnMath.atan2 ( This. Y, This. x); }};
As with data properties, accessor attributes can be inherited, and examples of the above code are as follows:
var q=inherit (p); // Create a new object that inherits the getter and setter Q.x=1,q.y=1; Console.log (Q.R); Console.log (Q.theta) ;
Vii. three properties of an object
Each object has three properties associated with the prototype (prototype), Class, and extensibility (extensible attribute).
1. Prototype properties
The prototype properties are set at the beginning of the instance object creation. objects created from direct amounts of objects use Object.prototype as their prototypes, and objects created by new use the prototype property of the constructor as prototypes. Objects created by Object.create () use the first parameter as a prototype.
To detect whether an object is a prototype of another object (or in a prototype chain), use the isPrototypeOf () method.
var p={x:1}; // defining a prototype object var o=object.create (p); // Use this prototype p to create an object op.isprototypeof (o) //trueObject.prototype.isPrototypeOf (o) //P inherits from Object.prototype
2. Class Properties
The class property of the object (class attribute) is a string that represents the type information of the object. To get the class of an object, you can call the object's ToString () method.
3. Scalability
The extensibility of an object is used to indicate whether a new property can be added to an object. All built-in objects and custom objects are explicitly extensible.
JavaScript authoritative Guide (6th edition) Learning Note Three