An advanced understanding of JavaScript objects and a comprehensive understanding of javascript

Source: Internet
Author: User
Tags tojson hasownproperty

An advanced understanding of JavaScript objects and a comprehensive understanding of javascript

To understand JavaScript objects, we can start with object creation, attribute operations, and object methods. To sum up, it includes the following modules:

1. Create an object

1.1 direct object volume

The direct volume of objects is the easiest way to create objects. A ing table consists of several name/value pairs:

var point = {x: 0, y: 0 };

There is no limit on the attribute name. It can be a js keyword or any string. In either case, the attribute needs to be caused by double quotation marks:

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. Code reusability is low. If you want to use this object elsewhere and the attribute values are different, do that? Do you have to create another code?

1.2 create an object through new

Before creating an object through new, you must create a function. new regards this function as a constructor ). For example, create a Person object using new:

Function Person () {// constructor} var person = new Person ();

The original types in the core of the Javscript language contain built-in constructors:

var a = new Array();var d = new Date();var r = new RegExp(“js”);

1.3 Object. create ()

Before learning about the Object's create method, we want to see what is a prototype. Every Javascript Object (except null) is associated with another object. Another object is what we call prototype. Each object inherits attributes from the prototype.

All objects directly created through objects have the same prototype Object. prototype. The new Keyword and the object prototype created by the constructor are the values of the prototype attribute of the constructor. 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. This section describes the prototype.

The Object. create method contains two parameters. The first parameter is the prototype of the Object, and the second parameter is optional. It is used to describe the Object attributes. It is easy to use. You only need to input the required prototype object:

Var o1 = Object. create ({x: 1, y: 2}); // The prototype is Object. prototype.

If you want to create an object without a prototype, you can pass in null as the parameter. The created object does not inherit any attributes, nor does it have a method like toString:

Var o2 = Object. create (null); // No prototype

If you want to create a common empty Object, directly input Object. prototype:

var o3 = Object.create(Object.prototype);

If it is a custom object, it is the same as creating an empty object. Directly input the object name. prototype:

function Person(){}var o4 = Object.create(Person.prototype);

2. Property Management

2.1 attribute query and setting

The attributes of an object can be obtained through the dot (.) or square brackets ([]) operator. If you use vertices to obtain attributes, the attribute name must be a simple identifier. It cannot be a reserved word, for example, 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 object ["property"] syntax looks more like an array, but the elements of this array are indexed by strings rather than digits. This array is what we call an associated array, also known as a hash, ing, or dictionary. Javascript objects are all associated arrays.

Since the object is an associated array, Javascript also provides us with an attribute Traversal method for/in. The following example uses for/in to calculate the total portfolio value:

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 attributes (own property), and some attributes are inherited from the prototype object. Let's take a look at the inheritance function inherit:

Function inherit (p) {if (p = null) throw TypeError (); // p is an Object, which cannot be null if (Object. create) {return Object. create (p); // directly use Object. create method} var t = typeof p; if (t! = "Object" & t! = "Function") throw TypeError (); function f () {}; f. prototype = p; // set its prototype property to p return new f ();}

Assume that the property x of object o is to be queried. If there is no x in o, the property x will be queried in o's prototype object. If the prototype object does not have x, but the prototype object also has the original type, the query continues on the prototype object, until x is found or an object whose prototype is null is found.

Var o ={}; // o from Object. prototype inherits the object property o. x = 1; // define the x attribute var p = inherit (o) for o; // p inherits o and Object. prototypep. y = 2; // p defines the property yvar q = inherit (p); // q inherits p, o, and Object. prototypeq. z = 3; // define the attribute zvar s = q for q. toString (); // toString inherits from Object. prototypeq. x + q. y // => 3: x and y inherit from o and p respectively.

2.2 Delete attributes

The delete operator can delete object attributes:

delete;delete book[“main title”];

Delete can only delete its own attributes, but cannot delete the inherited attributes. To delete an inherited property, you must delete it from the prototype object that defines this property, and this affects all objects inherited from this prototype. True is returned if the deletion is successful.

Ar o = {x: 1}; delete o. x; // delete x, returns truedelete o. x; // x does not exist, and returns true. Delete o. toString; // if nothing is done, true is returned. Delete cannot delete properties with a configuration type of false. Attributes of some built-in objects cannot be configured. For example, attributes of global objects created through variable declaration and function declaration: delete Object. prototype // cannot be deleted. The property is not configurable var x = 1; delete this. x; // the function f () {} delete this. f; // The global function cannot be deleted.

2.3 check attributes

You can use the in operator, hasOwnProperty (), and propetyIsEnumerable () methods to determine whether an attribute exists in an object.

In OPERATOR: the attribute name on the left side of the operator and the object on the right side. True is returned if the object has its own property or the inherited property contains the property:

Var o = {x: 1}; "x" in o; // true: x is the "y" in o; // false: y is not the "toString" in o; // true: o inherits the toString attribute.

HasOwnProperty () method: checks whether a given name is an object's own property. It returns false for the inherited attribute:

Var o = {x: 1}; o. hasOwnProperty ("x"); // true: o has a free property xo. hasOwnProperty ("y"); // false: The property yo. hasOenProperty ("toString"); // false: toString is an inherited property.

PropertyIsEnumerable () method: it is an enhanced version of hasOwnProperty. true is returned only when its own property is detected and its enumeration behavior is true:

Var o = inherit ({y: 2}); o. x = 1; o. propertyIsEnumerable ("x"); // true: o has its own property xo. propertyIsEnumerable ("y"); // false: y is an inherited Object. prototype. propertyIsEnumerable ("toString"); // false: enumeration not allowed

2.4 enumeration Properties

The for/in loop is usually used to traverse object attributes. The traversal attributes include their own attributes and inheritance attributes. The built-in methods of Object Inheritance cannot be enumerated, but the attributes added to the object in code can be enumerated. For example:

Var o = {x: 1, y: 2, z: 3}; // three self-owned property o that can be enumerated. propertyIsEnumeable ("toString"); // false, not enumerative for (p in o) // traverses the property console. log (p); // output x, y, and z, not toString

Sometimes we only want to traverse our own attributes, and the attributes are not functions:

for(p in o){  if(!o.hasOwnProperty(p)) continue;  if(typeof o[p] === "function") continue;}

We can use the enumeration traversal function to replicate enumeration attributes:

/** Copy the enumerated property in p to o and return o * If o and p contain the same name attribute, overwrite properties in o * This function does not process getter, setter, and replication properties */function extend (o, p) {for (prop in p) {// traverse all attributes in p. o [prop] = p [prop]; // Add attributes to o} return o ;}

ES5 defines two functions used to enumerate attribute names. The first is Object. keys (), which returns an array consisting of the enumerated property names of the Object. The second enumeration function is Object. getOwnPropertyNames (). Similar to Object. keys (), it returns all its own attributes, not just the enumerated attributes.

3. Attribute Encapsulation

3.1 attributes getter and setter

An object attribute consists of a name, a value, and a set of attributes. In ES5, the attribute value can be replaced by one or two methods. The two methods are getter and setter. The attributes defined by getter and setter are called "accessors attributes". Different from "data attributes", data attributes have only one simple value.

Unlike data attributes, the accessors attributes do not have writeable atrivity ). If the property has both the getter and setter methods, it is a read/write attribute. If it only has the getter method, it is a read-only attribute. If it only has the setter method, it is a write-only attribute. Read-Only attributes always return undefined.

The accessors attribute definition syntax is also relatively simple. Instead of using the function keyword, the function definition uses get or set:

Var o = {// common data attribute data_prop: 1, // accessors attributes are all pairs defined functions get accessor_prop () {/* here is the function body */}, set accessor_prop (value ){}};

Consider the following object that represents the coordinates of 2D Cartesian points. It has two common attributes, x and y, which represent the x and y coordinates respectively. It also has two equivalent accessors to represent the polar coordinates of points:

Var p = {// x and y are common read/write data attributes x: 1.0, y: 1.0, // r are read/write accessors attributes, it 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 the getter method get theta () {return Math. atan2 (this. y, this. x );}};

Like data attributes, accessors attributes can be inherited. Therefore, p objects in the above Code can be used as prototypes of another "point. The x and y attributes of a sex object can be defined, but the r and theta attributes inherit from:

var q = inherit(p);q.x = 1, q.y = 1;console.log(q.r);cosole.log(q.theta);

3.2 attribute features

We can regard the getter and setter methods of the accessors attributes as the attributes. According to this logic, we can also look at the attribute values as well as the attributes. Therefore, an attribute contains a name and four features.

The four features of a numeric attribute are value, writeable, enumerable, and configurable ).

Accessors attributes do not have the value Attribute and writability. Therefore, they include: get, set, enumeration, and configurability.

ES5 defines an object named "attribute descriptor", which represents the four features. The descriptor objects of data properties include value, writable, enumerable, and retriable. The descriptor object of the accessor attribute replaces the value and writable with the get and set attributes. Writable, enumerable, and retriable are both boolean values, and get and set attributes are function values.

You can call Object. getOwnPropertyDescriptor () to obtain the attribute descriptor of a specific Object attribute:

// Return {value: 1, writable: true, enumerable: true, retriable: true} Object. getOwnProeprtyDescriptor ({x: 1}, "x"); // query the octet attribute of the random object defined above. // return {get:/* func */, set: undefined, enumerable: true, retriable: true} Object. getOwnPropertyDesciptor (random, "octet"); // return undefinedObject for inherited and non-existent attributes. getOwnPropertyDesciptor ({}, "x"); Object. getOwnPropertyDesciptor ({}, "toString ");

From the function name, we can see that Object. getOwnPropertyDesciptor () can only get its own attribute descriptor. To obtain the property inheritance, You need to traverse the prototype chain (Object. getPrototypeOf ()).

If you want to set properties or make new properties have certain features, you need to call Object. defineProperty (), which contains three parameters: Object, attribute name, and attribute descriptor Object:

// Attributes exist, but do not enumerate o. x; // => 1Object. keys (o) // => [] // modify attribute x to make it a read-only Object. defineProperty (o, "x", {writable: true}); // view changes the value of this attribute o. x = 2; // The operation fails but no error is reported, but the type error thrown in strict mode is still configurable. Therefore, you can modify it in this way: object. defineProperty (o, "x", {value: 2}); o. x // => 2 // change x from data attribute to accessor attribute Object. defineProperty (o, "x", {get: function () {return 0 ;}}); o. x // => 0

If you want to modify or create multiple attributes 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 ing 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 APIs of getter and setter:Before ES5 was adopted, most Javascript implementations already support get and set writing in the object's direct amount syntax. These implementations provide non-standard old-fashioned APIs for querying and setting getter and setter. These APIs are composed of four methods, and all objects have these methods.

_ LookupGetter _ () and _ lookupSetter _ () are used to return the getter and setter methods of a naming attribute.

_ DefineGetter _ () and _ defineSetter _ () are used to define getter and setter. 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 attributes of an object

Each object has prototype, class, and extensible attribute ). Next, let's talk about the functions of these attributes.

4.1 prototype attributes

The prototype property of an object is used to inherit attributes. We often call "o's prototype property" directly "o's prototype ". Previously, "create object" introduced three methods to create objects. Objects directly created using objects use Object. prototype as their prototype. Objects Created using new use the prototype attribute of the constructor as their prototype. Objects Created using 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 the expression o. constructor. prototype is used to check the object prototype.

To check whether an object is a prototype of another object (or is in the prototype chain), use the isPrototypeOf () method. For example, you can use p. isPrototypeOf (o) to check whether p is an o prototype:

Var p = {x: 1}; // defines 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. prototype

The Javascript implemented by Mozilla exposes a special attribute named _ proto _, which is used to directly query/set the object prototype. However, IE and Opera do not support the _ proto _ attribute. Therefore, we do not recommend that you directly use the _ proto _ attribute.

4.2 class attributes

The class attribute of an object is a string used to indicate the type information of the object. Both ES3 and ES5 provide a method to set this attribute, and only one indirect method is available to query it. The default toString () method returns a string in this format: [object class].

You can call the toString () method and extract the characters between the eighth to the second to last position of the returned string. However, the trouble is that many toString () methods inherited by objects are overwritten. To call the correct toString () version, the Function. call () method must be called indirectly. 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, -1);}

4.3 scalability

Object scalability indicates whether new attributes can be added to an object. All built-in and custom objects are explicitly scalable. In ES5, the object can be converted to non-extensible.

The Object. seal () method can not only set the Object to non-extensible, but also set all its own attributes to non-configurable. That is to say, you cannot add new attributes to an object, and you cannot delete or configure existing attributes.

The Object. isSealed () method is used to check whether the Object is closed.

Object. the freeze () method will lock objects more strictly, except for having objects. in addition to the functions of the seal () method, you can set all the data attributes of the object to read-only (if the object's accessor attribute has a setter method, the accessors attribute will not be affected, you can still call them by assigning values to attributes ).

Object. isFrozen () is used to check whether the Object is frozen.

5. serialize objects

Object serialization refers to converting the object state to a string or restoring the string to an object. ES5 provides built-in functions JSON. stringify () and JSON. parse () for serialization and restoration of Javascript objects. These methods 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 the deep copy of o

JSON syntax is a subset of Javscript syntax. 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. The serialization results of NaN, Inifinity, and-Inifinity are both null. Functions, RegExp, Error objects, and undefined values cannot be serialized or restored.

Here, the method of adding an object is described as follows:

ToString () method:It returns 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. toStrring ().

ToJSON () method:The Object. prototype does not actually define the toJSON () method, but the JSON. stringify () method calls the toJSON () method for the Object to be serialized. If this method exists in a serialized object, call it.

ValueOf () method:The valueOf () method is very similar to the toString () method, but it is often called only when Javascript converts an object to an 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 fully understands all the content of the JavaScript Object advanced section is shared with you by xiaobian. I hope to give you a reference, and hope you can also support the help house.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.