Full understanding of JavaScript object Advanced _javascript Techniques

Source: Internet
Author: User
Tags arrays inheritance object object object serialization serialization tojson hasownproperty

To understand JavaScript objects, we can start with object creation, property manipulation, object methods. To sum up, include the following modules:

1. Creating objects

1.1 Object Direct Quantity

Object Direct volume is the simplest way to create an object, consisting of a number of name/value pairs that form the mapping table:

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

Property name also has no restrictions, can be JS keyword or any string, in both cases, the attribute needs 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"
}
;

Object Direct volume creation objects are simple, but are generally not used in this way. Code reusability is low, so if you want to use the object elsewhere and the property values are different, what do you do? Do you have to recreate a code again?

1.2 Creating objects from new

Before you create an object from new, you create a function, which is the constructor (constructor). For example, create a person object from new:

function person () {
//constructor
}

var person = new person ();

The original types in the Javscript language core 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 "other" object is what we call the archetype. Each object inherits attributes from the prototype.

All objects created by object Direct volume 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 by the new Array () is Array.prototype, and the object prototype created by the new Date () is Date.prototype. The prototype is introduced here.

The Object.create method contains two parameters, the first parameter is the object's prototype, and the second parameter is optional, which describes the object properties. Simple to use, just pass in the desired prototype object:

var O1 = object.create ({x:1, y:2}); Prototype for Object.prototype

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

var O2 = object.create (null); No prototypes.

If you want to create an ordinary empty object, pass in the Object.prototype directly:

var O3 = object.create (Object.prototype);

If it is a custom object, it is the same as creating an empty object. Pass directly to the object name. Prototype:

function person () {
}
var O4 = object.create (Person.prototype);

2. Attribute Management

2.1 Property queries and Settings

The properties of an object can be obtained by point (.) or square brackets ([]) operators. If you use a point to get a property, the property name must be a simple representation. Cannot be reserved words, 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

Object["Property" This syntax looks more like an array, except that the elements of the array are indexed by a string rather than a numeric index. This array is what we call an associative array, also called a hash, a map, or a dictionary. JavaScript objects are associative arrays.

Now that the object is an associative array, JavaScript also provides us with a way to iterate over the attributes for/in. The following example uses For/in to compute the total value of portfolio:

function GetValue (portfolio) {
  var total = 0.0;
  For (the stock in Portolio) {
    var shares = Portolio[stock];
    var = getquote (stock);
    Total + = shares * price;
  }

  return total;
}

Inheritance: JavaScript objects have their own properties (own property), and some properties are inherited from a prototype object. Let's take a look at a function that implements the inheritance function inherit:

function inherit (p) {
  if (p = = null) throw TypeError ();//p is an object, large cannot be null
  if (object.create) {return
    Object.create (P); Directly using the 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 ();
}

Suppose you want to query the property X of Object o, and if X does not exist in O, you will continue querying the property X in the prototype O object. If there is no X in the prototype object, but the prototype object also has a prototype, continue to execute the query on the prototype of the prototype object until an X is found or an object with a prototype null is queried.

var o = {}; o Inherit object attribute from Object.prototype
= 1;//give o define x attribute
var p = inherit (o);//p inheritance O and object.prototype
p.y = 2;//p Define Properties y< C4/>var q = Inherit (p); Q inheritance P, O and object.prototype
q.z = 3; to q define attribute Z
var s = q.tostring ();//tostring inherits from Object.prototype q.x
+ q.y/ /=> 3:x and y inherit from O and P respectively

2.2 Delete Attributes

The delete operator can delete an object's properties:

Delete Book.author;
Delete book["main title"];

Delete can only delete its own properties and cannot delete inherited properties. To delete an inherited property, you must remove it from the prototype object that defines the property, and this affects all objects that inherit from this prototype. A successful deletion will return true.

Ar o = {x:1};
Delete o.x; Delete x, return true
delete o.x;//x no longer exists, nothing has done, return true.
delete o.tostring;//Nothing done, return true.
Delete Cannot delete a property that can be configured to False. The properties of some of the built-in objects are not configurable, such as the properties of global objects created by variable declarations and function declarations:
Delete object.prototype//cannot be deleted, property is not configurable
var x = 1;
Delete this.x; Cannot delete this property function
F () {}
delete this.f;//Cannot delete global function

2.3 Detection Properties

To determine whether an attribute exists in an object, it can be detected by the in operator, the hasOwnProperty (), and the Propetyisenumerable () method.

In operator: The left side of the operator is the property name and the right side is the object. Returns true if the object's own property or inherited property contains a property:

var o = {x:1};
X "in O; True:x is O's property
"Y" in O;//false:y is not O's property
"ToString" in O;//true:o Inherits ToString Property

hasOwnProperty () Method: detects whether a given name is an object's own property. For an inherited property, it returns false:

var o = {x:1};
O.hasownproperty ("X"); True:o has a free attribute
of x o.hasownproperty ("Y"); Property y
o.hasoenproperty ("toString") does not exist in//false:o; False:tostring is an inherited property

propertyIsEnumerable () Method: is an enhanced version of hasOwnProperty that returns true only if its own properties are detected and this property is removable to true:

var o = inherit ({y:2});
o.x = 1;
O.propertyisenumerable ("X"); True:o has an enumerable of its own properties x
o.propertyisenumerable ("Y");//false:y is inherited
. Object.prototype.propertyIsEnumerable ("toString"); False: Not enumerable

2.4 Enumeration Properties

You typically use for/in loops to traverse object properties, and the properties that are traversed include both own and inherited properties. The built-in methods of object inheritance are not enumerable, but the attributes that are added to the object in code are enumerable. For example:

var o = {x:1, y:2, z:3}; Three enumerable own property
o.propertyisenumeable ("toString");//false, not enumerable for
(P in O)//Traverse attribute
  Console.log (p);//Output X, Y and Z, will not output ToString

Sometimes we just want to traverse our own property, and the property is not a function:

For (P in O) {
  if (!o.hasownproperty (p)) continue;
  if (typeof o[p] = = "function") continue;
}

We can implement the replication of enumerable properties by enumerating traversal functions:


* * Copy the enumerable attribute in P to O and return o
* If O and P contain attributes with the same name, the property in O is overwritten
* This function does not deal with Getter and setter and copy attributes/
function Extend (o, p) {
  for (prop in P) {//Traverse all properties in P
    o[prop] = P[prop];///Add property to O} return
  o;
}

ES5 defines two functions that enumerate property names. The first is Object.keys (), which returns an array of the names of the enumerable properties in the object. The second enumeration function is Object.getownpropertynames (), similar to Object.keys (), which returns all of its own properties, not just enumerable properties.

3. Attribute Encapsulation

3.1 Property getter and setter

Object attributes consist of a name, a value, and a set of attributes (attribute). In ES5, property values can be replaced with one or two methods, which are getter and setter. Properties defined by getter and setter are called accessor properties, which are different from data properties and have a simple value for data properties.

Unlike data properties, accessor properties are not writable (writeable Atribute). If the attribute has both getter and setter methods, then it is a read/write property. If it has only the getter method, then it is a read-only property, and if it has only a setter method, it is a write-only property. Reading a write-only property always returns undefined.

Accessor property definition syntax is also relatively simple, function definitions do not use the Functions keyword, but use GET or set:

var o = {
  //Normal data attribute
  data_prop:1,
  //accessor properties are pairs-defined functions get
  accessor_prop () {/* Here is the function body/},
  set accessor _prop (value) {}
};

Consider the following object that represents the 2D Cartesian point coordinates. It has two normal properties X and y represent the x and Y coordinates, and there are two equivalent accessor properties used to represent the polar coordinates of a point:

var p = {
  //x and y are normal read-write data Properties
  x:1.0,
  y:1.0,
  //r is a read-write accessor property, 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 property, only getter method get
  Theta () {return math.atan2 (This.y, this.x);}
;

As with data properties, accessor properties can be inherited, so the P object in the above code can be used as a prototype of another "point". You can define its X and Y properties for a sexual object, but R and Theta properties inherit:

var q = Inherit (p);
q.x = 1, q.y = 1;
Console.log (Q.R);
Cosole.log (Q.theta);

3.2 Attribute Attributes

We can consider the getter and setter methods of accessor properties as attributes. By this logic, we can also look at the attribute's value as well as the attribute. Therefore, one attribute can be considered to contain a name and 4 attributes.

The 4 attributes of a numeric attribute are its values (value), the writable (writeable), the enumerable (enumerable), and the configurable type (configurable).

Accessor properties do not have values (value) attributes and are writable, and therefore contain: Read (get), write (set), enumerable, configurable.

ES5 defines an object named "Property Descriptor", which represents the 4 attributes. The properties of the descriptor object for the Data property are value, writable, enumerable, and configurable. The descriptor object for accessor properties replaces value and writable with the Get property and the Set property. Where writable, enumerable, and configurable are Boolean values, get and set properties are function values.

You can get a property descriptor for an object-specific property by calling Object.getownpropertydescriptor ():

Returns {value:1, Writable:true, Enumerable:true, configurable:true}
object.getownproeprtydescriptor ({x:1}, "X"); c2/>//Query The octet attribute of the random object defined above
//return {get:/*func/, set:undefined, Enumerable:true, configurable:true}
Object.getownpropertydesciptor (Random, "octet");

Returns undefined
object.getownpropertydesciptor ({}, "X") for inherited and nonexistent attributes;
Object.getownpropertydesciptor ({}, "toString");

From the function name, it can be seen that object.getownpropertydesciptor () can only get the descriptor of its own property. To get the attributes of an inherited property, you need to traverse the prototype chain (Object.getprototypeof ()).

To set attributes for a property, or to have a new attribute with certain attributes, you need to invoke Object.defineproperty (), which contains three parameters: Object, property name, property descriptor object:

property is present, but cannot be enumerated
o.x//=> 1
object.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
o.x = 2;//The operation fails without an error, and the exception
//attribute is still configurable in strict mode, so it can be modified in this way:
Object.defineproperty (o , "X", {value:2});
o.x//=> 2
//Now modify X from data properties to accessor Properties
object.defineproperty (O, "x", {get:function () {return 0;}});
o.x//=> 0

If 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 modify, and the second parameter 㐊 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
  }
});

Vintage APIs for getter and setter: prior to ES5 adoption, most JavaScript implementations can already support get and set notation in object Direct-volume syntax. These implementations provide non-standard, old-fashioned APIs for querying and setting getter and setter. These APIs consist of four methods, all of which are owned by all objects.

__lookupgetter__ () and __lookupsetter__ () are used to return the getter and setter methods of a named property.

__definegetter__ () and __definesetter__ () define the getter and setter, the first parameter is the property 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. Object's three properties

Each object has its associated prototype (prototype), Class (Class), Extensibility (extensible attribute). The next step is to tell what these attributes do.

4.1 Prototype Properties

The prototype properties of an object are used to inherit attributes, and we often call the "O prototype" directly "O's prototype". The "Create object" before describes three ways to create an object. objects created with direct amounts of objects use Object.prototype as their prototypes. Objects created from new use the prototype property of constructors as their prototypes. Objects created by Object.create () use the first parameter as their prototypes.

In ES5, object prototypes can be queried by object.getprototypeof (). In ES3, there is no function equivalent to it, but instead uses an expression O.constructor.prototype to examine the object's prototype.

To detect whether an object is a prototype of another object (or in a prototype chain), use the isPrototypeOf () method. For example, a p.isprototypeof (O) can be used to detect whether P is a prototype of 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 P
Object.prototype.isPrototypeOf (o)//=> True, p inherits from Object.prototype

Mozilla-implemented JavaScript exposes a specially named __proto__ attribute to directly query/set object prototypes. However, ie and opera do not support __proto__ properties, so it is not recommended to use the __proto__ property directly.

4.2 Class Properties

The class property of an object is a string that represents the type information of the object. Both ES3 and ES5 provide a way to set this property, with only one indirect way of querying it. The default ToString () method returns a string in this format: [Object class].

You can then extract the characters between the eighth and penultimate positions of the returned string by calling the ToString () method. But the trouble is that many object-inherited ToString () methods have been overridden to invoke the Function.call () method indirectly in order to be able to invoke the correct ToString () version. The Classof function of the following example returns 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 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. In ES5, you can convert an object to an extensible.

In addition to being able to set an object to be extensible, the Object.seal () method can also set all its own properties to be not configurable. That is, you cannot add new attributes to an object, and existing properties cannot be deleted and configured.

The object.issealed () method is used to detect whether an object is closed.

The Object.freeze () method will more tightly lock objects, in addition to the functionality of the Object.seal () method, you can set all of its own data properties to be read-only (if the object's accessor properties have setter methods, accessor properties are not affected, They can still be called by assigning values to properties.

Object.isfrozen () is used to detect whether an object is frozen.

5. Serialization of objects

Object serialization refers to converting the state of an object to a string, or to reverting a string to an object. ES5 provides built-in functions json.stringify () and Json.parse () to serialize and restore JavaScript objects. These methods use JSON as the data Interchange 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 O

The syntax of JSON is a subset of the Javscript syntax, and it does not represent all the values in JavaScript. Supports objects, arrays, strings, infinity digits, True, false, and null, and they can be serialized and restored. The results of NaN, inifinity, and-inifinity serialization are null. Functions, REGEXP, Error objects, and undefined values cannot be serialized and restored.

Here's how to add the object:

toString () method: It returns a string representing the value of the object that called the method. Many objects have rewritten the toString () method, such as array.tostring (), date.tostring (), and function.tostrring ().

Tojson () method: Object.prototype actually does not define the Tojson () method, but the Json.stringify () method invokes the Tojson () method because of the object that needs to execute the serialization. If this method exists in an object that is serialized, it is called.

valueof () method:the ValueOf () method is very similar to the ToString () method, but it is often the case that JavaScript needs to convert an object to a primitive 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 a comprehensive understanding of JavaScript object Advanced is a small series to share all the content, hope to give you a reference, but also hope that we support the cloud-dwelling community.

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: info-contact@alibabacloud.com 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.