A detailed explanation of the JavaScript Authority Guide's object _javascript skills

Source: Internet
Author: User
Tags arrays object serialization reserved serialization hasownproperty

JavaScript objects can be viewed as unordered collections of attributes, each of which is a pair of key values that can be added to the deletion.

Everything in JavaScript is an object: A string, a number, an array, a date, and so on.

In addition to maintaining its own properties, JavaScript objects can inherit properties from an object called a prototype. The method of an object is usually an inherited property. This "prototyping integration" is the core feature of JavaScript.

1. Creating objects

The first: Object direct-volume notation creates an object.

This is the simplest way to create an object, which consists of a number of Key:value key values that are separated by commas, and the entire object is enclosed in curly braces.

var empty = {}; object with no attributes var point
= {x:3, y:5};//object containing two properties
var Point2 = {x:point.x + 1, Y:point.y + 1};//property value can be an expression C6/>var book = {
"main title": "JavaScript",///property name has spaces, must be represented by a string
"sub-title": "The Defintive Guide",//property name has a hyphen, "For" must be represented by a string
: "All audiences",//property name is a reserved word and must be represented by
a string author: {//The value of this property is an object
firstname: "David",
Surname: "Flanagan"
}

In ECMAScript version 5, you can use reserved word property names without quotes. The comma is automatically ignored when the last property of the object is directly measured.

Second: Create objects from keywords.

The keyword new is used to create and initialize objects, followed by a constructor. The original types in the JavaScript language core contain built-in constructors, and the following is a built-in object creation demo.

var o = new Object (); Creates an empty object, equivalent to 0={}
var a = new Array ();//Create an empty array
var d = new Date ()///Create a Date object that represents the current time
var r = new RegExp (" JS "); Create a regular Expression object

In addition to these built-in constructors, it is also common to use a custom constructor to initialize new objects.

Before you introduce the third method, you need to understand the concept of "prototype" first. Each JavaScript object (except NULL) has an associated object and can inherit the property from the associated object. This association object is the so-called "prototype", similar to the base class in C #.

All objects created from object direct quantities and constructors can obtain a reference to a prototype object through Object.prototype. Object.prototype is one of the few objects without a prototype.

Ordinary objects have prototypes, such as the array.prototype of an array array object. Also, built-in constructors have a prototype that inherits Object.prototype. Therefore, the properties of an array object created by the new array () are inherited to both Array.prototype and Object.prototype, and when the object has multiple inheritance relationships, the prototype object of this series of links is called the "prototype chain."

Third: Create objects using the Object.create () function.

Object.create (Object[,properties]) is a static function that appears in the ECMAScript version 5 to create an object. It receives two parameters: the first is the prototype to create the object, and the second is an optional parameter that describes the object's properties.

Use it to create an object, just pass in the desired prototype object:

var a = object.create ({' Islock ': true}); Specifies a prototype
console.log (A.islock) for object A;//=> true o inherits the prototype object properties Islock

To create a plain empty object, you need to pass in the parameter object.prototype:

 
 

You can create an object without a prototype by passing in parameter null, which does not inherit anything:

 
 

Creating an object from a prototype allows any object to inherit, which is a powerful feature. For example, you can prevent programs from unintentionally modifying objects that are not controlled. Instead of manipulating the object directly, the program operates an inherited object created by Object.create ().

2. Querying and Setting properties

object property values can be queried or set by the point. and bracket [] operators.

var book = {' author ': ' Tom ', ' main title ': ' Hello JavaScript '};
var author = book.author; 1. Get book's "Author" property value
var title = book["Main title"]//2. Gets the book's "Main title" property value
book.edition = 6;//3. Create a "edition" property for book

In the ES3 version, if the property name is a keyword, it must be accessed through the form of square brackets. The ES5 version relaxes the requirement to use reserved words directly after the dot operator.

Associative array objects

The above mentioned that you can manipulate object properties by object["Property", which looks more like an array, except that the array element is indexed by a string rather than a numeric index, which is called an associative array. JavaScript objects are associative arrays that, when accessed by [], can be created or modified when the program is run, with more flexibility.

Inherited

The properties of a JavaScript object are divided into two types, one defined by itself and called the "owning property". There are also some attributes inherited from the prototype object. The multiple inheritance relationships of object attributes form the prototype chain.

Object properties Check the prototype chain before assigning values to determine whether an assignment operation is allowed. For example, if the object o inherits from a read-only property x, assigning a value to the X property is not allowed. If a property is allowed to be assigned a value, it is only created on the original object or assigned a value to an existing property, without modifying the prototype chain.

In JavaScript, it is generally only when querying properties that the inheritance exists, and setting properties is independent of inheritance. This feature allows you to selectively overwrite inherited properties.

Property Access Error

Querying for a nonexistent property does not complain. Returns undefined if the specified property is not found in the object's own properties and inherited properties. Verify by following a short piece of code:

var a = {name: ' admin '}; Define a prototype object a
var b = object.create (a);//Define an object B to inherit to object a
console.log (b.name);//=> Admin B Inherits A's Name property, normal output

But there is a situation where if an object does not exist, an attempt to access the properties of the nonexistent object throws an exception. For example:

Console.log (C.name); Uncaught REFERENCEERROR:C is not defined
var d = null;

So, this requires us to verify the access to the properties of the indeterminate object.

var book = {"Length":};
var len = book && book.length; This replaces if with the third use of &&.

3. Delete Attributes

The delete operator can delete an object's properties, and the deletion succeeds in returning true. However, delete cannot delete properties that are configurable to false. You can delete only its own properties and cannot delete inherited properties.

 
 

When you delete a global property, you can omit the global object directly, followed by the property you want to delete.

This.x=1; Create a global property

4. Detection Properties

The so-called detection property is to determine the existence of an attribute and an object. Validation can generally be done using the in operator, hasOwnProperty (), and propertyisenumerable () methods.

The In operator determines if the object's own property or inherited property contains this property to return true.

var o = {"X": 5};
Console.log ("x" in O); =>true object o has attributes x
console.log ("Y" in O);//=>false object o has no attributes x
console.log ("toString" in O);//=>true Object O Inheritance Property tostring 
hasOwnProperty () method is used to detect whether a given property is an object's own property and false for an inherited property.
var o = {"X": 5};
Console.log (O.hasownproperty ("X")); =>true
Console.log (O.hasownproperty ("toString"));//=>false 
propertyisenumerable () The method is an enhanced version of hasOwnProperty (). Returns true only if the property is detected as an object's own property and this property is enumerable.
var o = object.create ({"Y": 5});
o.x = 6;
Console.log (O.propertyisenumerable ("X")); =>true x is the own property
Console.log (o.propertyisenumerable ("Y"));//=>false y is an inherited property

5. Property accessor

In ECMAScript 5, objects can define protected properties like C #, Java, and other advanced languages using get and set keywords. This property is called an accessor property, and it can be inherited.

var obj = {
//Data attribute (can be viewed as field)
Data:null,
//accessor Property (Protection property) get
data () {return this.data;},
set data (value ) {this.data = value;}
;
Obj. Data = "admin";

How about, there is no feeling and Java in the protection properties of the writing is very similar. Because JavaScript itself is an object-oriented programming language.

If an object property has both a get and a set method, it is a read/write property. If the property has only one get method, then it is a read-only property. If the property has only one set method, then it is a write-only property, and the read-only property always returns undefined.

6. Attributes of properties

The properties of an object are writable, configurable, and enumerable under the ECMAScript 3 version, but by ECMAScript 5 The attribute is a property that can be identified by some APIs as writable, configurable, and enumerable. This API is also known as attribute properties.

• 4 characteristics of ordinary data properties: value (values), writable (writable), enumerable (enumerable), configurable (configurable).

• 4 features of the memory properties: Get (Read), set (write), Enumerable (enumerable), configurable (configurable).

ECMAScript 5 defines a object.getownpropertydescriptor () method that is used to query the attributes of an object-specific property, and returns a property descriptor object that represents the 4 attributes of an object's properties.

var descriptor = Object.getownpropertydescriptor ({length:50}, "Length");
Console.log (descriptor); 
=> descriptor = {value:50, writable:true, Enumerable:true, configurable:true}
//--------------------------- ---------------------------------------
var random = {
//read-only property: Returns a random number between 0-255
octet () {return Math.floor (Math.random () * 256); }
};
var descriptor1= object.getownpropertydescriptor (Random, "octet");
Console.log (Descriptor1); 
=> Descriptor1 = Object {set:undefined, enumerable:true, configurable:true}

It can be seen from the name that the method can only get the descriptor of the object's own property, so for the inherited property and nonexistent attribute, return undefined. To get the attributes of an inherited property, you need to traverse the prototype chain.

To set a property or have an attribute on a newly created property, you need to call the Object.defineproperty () method, the first parameter is the object to be modified, the second is the property to modify, and the third is the property descriptor object. The returned value is a modified copy of the object.

var o = {}; Create an empty object
object.defineproperty (o, "x", {
value:1,//define an X property, assign a value of 1
writable:true,//writable
enumerable: False,//non-enumerated
configurable:true//Configurable
});
if (o.x) Console.log (Object.keys (o)); => props = [] property exists, but cannot enumerate
object.defineproperty (o, "x", {writable:false});//Let property x become read-only
o.x = 2;//Attempt to modify the value of property X Failure, but no error
Console.log (o.x);//=>1 
object.defineproperty (o, "x", {value:2});//But property X is still configurable and can directly modify the value attribute.
Console.log (o.x);//=>2
Object.defineproperty (O, "x", {//Modify data properties to accessor Properties
get:function () {return
0;
}
});
Console.log (o.x); =>0

This method also fails to set attributes for inherited properties. You can use the Object.defineproperties () method if you need to modify attributes of multiple own properties at the same time. The first parameter is the object to modify; the second parameter is a mapping table object that contains the property name and the descriptor object for the corresponding property.

var p = object.defineproperties ({}, {
x: {value:3, writable:true, Enumerable:true, configurable:true},
y: { Value:4, Writable:true, Enumerable:true, configurable:true},
r: {
get:function () {return
math.sqrt (thi S.x * this.x + this.y * this.y);
},
enumerable:true,
configurable:true
}
});
Console.log (P.R); =>5

7. Object's three properties

Prototype properties

The object's prototype is used to inherit the attribute, which is so important that it often calls the "O prototype" directly "O's prototype".

The prototype property is set at the beginning of the object creation. The prototype has been introduced before, but it is still to be added here.

• Objects created by direct volume of objects use Object.prototype as prototypes;

• Objects created by the New keyword use the prototype of the constructor as a prototype;

• Objects created by object.create () use the first parameter as a prototype.

In the ES5 version, the object is passed into the object.getprototypeof () method to query its prototype object.

You can use the isPrototypeOf () method to detect if an object is a prototype of another object.

var a = {X:2};
var B = Object.create (a);
Console.log (a.isprototypeof (b)); => true
Console.log (Object.prototype.isPrototypeOf (b));//=> true

Class properties

The class property of an object is a string that represents the type information for the object. But JS does not provide a direct query method, only an indirect method query, you can call the object's ToString () method, and then extract the return string of the 8th character to the penultimate position between the characters. If the ToString () method of an object inheritance is overridden, it must be invoked indirectly through the Function.call () method.

function Classof (o) {
if (o = = null) return "NULL";
if (o = = = undefined) return "undefined";
return Object.prototype.toString.call (o). Slice (8,-1);
}

Classof () can receive any type of parameter, and the function contains special handling for null and undefined.

Console.log (classof (null)); => "Null"
Console.log (classof (1));//=> "Number"
Console.log (Classof ("")); => "String"
Console.log (Classof (false);//=> "Boolen" Console.log
(Classof ({});//=> "Object"
Console.log (Classof (/./));//=> "Regexp"
console.log (classof (window);//=> "Window" (browser Host object class)

Scalability

An extensible row of an object is used to indicate whether a new property can be added to an object. ECMAScript version 5, all custom objects, built-in objects, and host objects default to support extensibility. Here are a few ways to detect and set object extensibility and the differences between them.

The Object.preventextensions () method can set an incoming object to be extensible. The two points to note are: 1. Once an object becomes extensible, it cannot be converted to extensible; 2. If you add attributes to a prototype of an object that is not extensible, the object will inherit these new properties as well.

The Object.isextensible () method can detect the extensibility of incoming objects.

The Object.seal () method sets the incoming object to be extensible and sets all its own properties to be not configurable. That is, you cannot add new attributes to this object, and you cannot delete or configure existing properties. The object.issealed () method can be used to detect whether an object is closed, as it cannot be unsealed for an object that has already been sealed.

The Object.freeze () method is more "ruthless", and it freezes the object directly. All data properties of an object's own properties are set to read-only properties, in addition to setting the object to be extensible and its properties set to not configurable. You can use the Object.isfrozen () method to detect whether an object is frozen.

Object.preventextensions (), Object.seal (), and Object.freeze () three methods return the incoming object.

8. Serialization of objects

I'm sure you're not unfamiliar with JSON, but this section is about JSON serialization. Serialization is the conversion between JS objects and strings, JSON as a data interchange format. ECMAScript 5 provides two built-in functions json.stringify () and Json.parse () to serialize and restore a JS object.

var obj = {x:3, y:5}; Defines a test object
var str = json.stringify (obj);//str = "{" X ": 3," Y ": 5}"
obj = Json.parse (str);//obj = object {x:3, y: 5}

The full name of JSON is the "JavaScript Object Notation"---javascript objects notation. The JSON syntax does not represent all of the values in JavaScript. Supports serialization and restoration of objects, NaN, arrays, strings, infinity digits, true\false, and null. Functions, REGEXP, Error objects, and undefined values cannot be serialized and restored. The Json.stringify () function can only serialize its own properties that can be enumerated by the object. The result of a Date object serialization is an ISO-formatted date string.

The above is a small set to introduce the JavaScript Authority guide to the object, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

Related Article

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.