Summary of JavaScript objects, javascript objects

Source: Internet
Author: User
Tags hasownproperty

Summary of JavaScript objects, javascript objects

Summary of Javascript objects:

JavaScript objects can be seen as unordered sets of attributes. Each attribute is a key-Value Pair and can be added or deleted.

All things in JavaScript are objects: strings, numbers, arrays, dates, and so on.

In addition to retaining its own attributes, JavaScript objects can also inherit attributes from a prototype object. Object methods are generally inherited attributes. This "original type integration" is the core feature of JavaScript.

1. Create an object

First, create an object using the object Direct Volume representation.

This is the simplest way to create an object. The object quantity is composed of several key: value key-value pairs. attributes are separated by commas, and the entire object is enclosed in curly brackets.

Var empty ={}; // The object var point = {x: 3, y: 5} that does not contain any attribute; // The object var point2 = {x: point. x + 1, y: point. y + 1}; // The attribute value can be the expression var book = {"main title": "JavaScript", // The attribute name has spaces, you must use a string to indicate "sub-title": "The Defintive Guide", // The property name is a hyphen, and must use a string to indicate "for": "all audiences ", // The property name is a reserved word and must use a string to indicate author: {// the value of this property is an object firstname: "David", surname: "Flanagan "}

In ECMAScript 5, reserved word attribute names can be used without quotation marks. The object is automatically ignored after the last attribute is measured with commas.

Type 2: Create an object with a keyword.

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

Var o = new Object (); // create an empty Object, equivalent to 0 ={} var a = new Array (); // create an empty array var d = new Date (); // create a Date object var r = new RegExp ("js") representing the current time "); // create a regular expression object

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

Before introducing the third method, you must first briefly understand the concept of "prototype. Each JavaScript Object (except null) has an associated object and can inherit attributes from the associated object. This correlated object is called "prototype", similar to the base class in C.

All objects created through the Object direct volume and constructor can be referenced by the prototype Object. There are few objects without prototypes, and Object. prototype is one of them.

Common objects have original types. For example, the prototype of an Array object is Array. prototype. At the same time, all built-in constructors have a prototype that inherits Object. prototype. Therefore, the attributes of the Array object created through new Array () are inherited to Array. prototype and Object. prototype: when an object has multiple inheritance relationships, the prototype of the link is called the prototype chain ".

Third: Use the Object. create () function to create an Object.

Object. create (Object [, Properties]) is a static function in ECMAScript 5 that is used to create objects. It receives two parameters: the first is the prototype of the object to be created, and the second is the optional parameter used to describe the object attributes.

To create an object, you only need to input the required prototype object:

Var a = Object. create ({'islock': true}); // specify a prototype console for object. log (. isLock); // => true o inherits the attributes of the prototype object isLockconsole. log (. hasOwnProperty ('islock'); // => false verify that isLock is not an o's own attribute

To create a common null Object, you must input the Object. prototype parameter:

Var B = Object. create (Object. prototype );

You can pass in the null parameter to create an object without a prototype, which does not inherit anything:

Var B = Object. create (null); // This Object does not include any basic methods of the Object

By creating an object through a prototype, any object can be inherited, which is a powerful feature. For example, it can prevent the program from inadvertently modifying uncontrolled objects. The program does not directly operate on objects, but operate on inherited objects created through Object. create.

2. query and Set Properties

Object Property values can be queried or set through the dot and square brackets [] operators.

Var book = {'author': 'Tom ', 'main title': 'Hello JavaScript'}; var author = book. author; // 1. obtain the "author" attribute value var title = book ["main title"]; // 2. obtain the "main title" attribute value book of the book. edition = 6; // 3. create a "edition" attribute for book ["main title"] = "ECMAScript"; // 4. modify the attribute value of "main title"

In ES3, if the attribute name is a keyword, it must be accessed in square brackets. ES5 allows you to use reserved words directly after the dot operator.

Associate an array object

As mentioned above, object ["property"] can be used to operate object properties. This syntax looks more like an array, but this array element is indexed by a string instead of a numeric index. Such arrays are called associated arrays. JavaScript objects are all associated arrays. When you access object attributes through [], you can create or modify them while running the program, which is more flexible.

Inheritance

JavaScript objects have two types of attributes. One is self-defined and called "self-owned attributes ". Some attributes are inherited from the prototype object. The multi-inheritance relationships of Object Attributes constitute the prototype chain.

Before assigning a value, the object attribute checks the prototype chain to determine whether the value assignment operation is allowed. For example, if the object o inherits from a read-only attribute x, the value assignment to the x attribute is not allowed. If attribute assignment is allowed, the original object is created or the existing attribute is assigned a value without modifying the prototype chain.
In JavaScript, the existence of inheritance can be realized only when attributes are queried, and the property setting is irrelevant to inheritance. You can use this feature to overwrite the inherited attributes.

Attribute Access Error

No error is returned when querying a property that does not exist. If the specified attribute is not found in the object's own attributes and inherited attributes, undefined is returned. Use the following code to verify:

Var a = {name: 'admin'}; // defines a prototype Object avar B = Object. create (a); // defines an object B inherited to the object aconsole. log (B. name); // => admin B inherits the name attribute of a and outputs the console normally. log (B. age); // => undefined bits and inherited objects do not have the age attribute, so the output is undefined.

However, if the object does not exist, an exception is thrown when you try to access the property of the nonexistent object. For example:

console.log(c.name); //Uncaught ReferenceError: c is not definedvar d = null;console.log(d.name); //Uncaught TypeError: Cannot read property 'name' of null

Therefore, this requires us to verify the access to uncertain object attributes.

Var book = {"length": 21}; var len = book & book. length; // replace if with the third usage of & here. Console. log (len); // => 21

3. Delete attributes

The delete operator can delete the attributes of an object. If the object is deleted successfully, true is returned. However, delete cannot delete properties with the configuration type of false. Only attributes of the current user can be deleted. inherited attributes cannot be deleted.

Delete book. author // return true

When deleting a global attribute, You can omit the global object directly. The delete object is followed by the attribute to be deleted.

This. x = 1; // create a global property console. log (delete x); // => true

4. Check attributes

The so-called detection attribute is to judge whether an attribute exists in a specific object. Generally, you can use the in operator, hasOwnProperty (), and propertyIsEnumerable () Methods to complete the verification.

The in operator determines that if the object has its own property or the inherited property contains this property, true is returned.

Var o = {"x": 5}; console. log ("x" in o); // => true object o has the property xconsole. log ("y" in o); // => false object o has no attribute xconsole. log ("toString" in o); // => true object o inherited attribute toString

The hasOwnProperty () method is used to check whether a given property is an object's own property. If it is an inherited property, false is returned.

var o = { "x": 5 };console.log(o.hasOwnProperty("x")); //=>trueconsole.log(o.hasOwnProperty("toString")); //=>false

The propertyIsEnumerable () method is an enhanced version of hasOwnProperty. True is returned only when the property is an object's own property and the property is enumerative.

Var o = Object. create ({"y": 5}); o. x = 6; console. log (o. propertyIsEnumerable ("x"); // => true x indicates that the console has its own properties. log (o. propertyIsEnumerable ("y"); // => false y inherits the property console. log (Object. prototype. propertyIsEnumerable ("toString"); // => false toString cannot be enumerated

5. Attribute accessors

In ECMAScript 5, objects can use the get and set keywords to define protection attributes like C #, Java, and other advanced languages. This type of attribute is called an accessor attribute, which can be inherited.

Var obj = {// data attributes (which can be viewed as fields) Data: null, // accessors attributes (Protection attributes) get data () {return this. data;}, set Data (value) {this. data = value ;}}; obj. data = "admin"; console. log (obj. data); // => admin

How do you feel like writing protection attributes in JAVA. JavaScript itself is an object-oriented programming language.
If the object property has both get and set methods, it is a readable/Write attribute. If the attribute has only one get method, it is a read-only attribute. If the attribute has only one set method, it is a write-only attribute, and the read-only attribute always returns undefined.

6. Attributes

Whether the attributes of objects in ECMAScript 3 are writable, configurable, and enumerable, however, in ECMAScript 5, attributes can be used to identify whether they are writable, configurable, and enumerative. This API is also called the property feature.
Four features of common data attributes: value, writable, enumerable, and configurable ).
Four features of memory attributes: get, set, enumerable, and configurable ).
ECMAScript 5 defines an Object. getOwnPropertyDescriptor () method to query the characteristics of a specific Object property. It returns an "attribute descriptor" Object, which represents four properties of the Object property.

Var descriptor = Object. getOwnPropertyDescriptor ({length: 50}, "length"); console. log (descriptor); //> descriptor = {value: 50, writable: true, enumerable: true, retriable: true} // specify var random = {// read-only attribute: returns a random number between 0 and get octet () {return Math. floor (Math. random () * 256) ;}}; var descriptor1 = Object. getOwnPropertyDescriptor (random, "octet"); console. log (descriptor1); // => descriptor1 = Object {set: undefined, enumerable: true, retriable: true}

From the name, we can see that this method can only obtain the descriptor of the object's own attributes. Therefore, for the inherited and non-existent attributes, undefined is returned. To obtain the properties of the inherited attributes, You need to traverse the prototype chain.

To set attributes or make new attributes have certain features, you need to call the Object. defineProperty () method. The first parameter is the object to be modified, the second parameter is the attribute to be modified, and the third parameter is the attribute descriptor object. The returned value is the modified object copy.

Var o ={}; // create an empty Object. defineProperty (o, "x", {value: 1, // defines an x attribute, assigned a value of 1 writable: true, // writable enumerable: false, // cannot enumerate retriable: true // configurable}); if (o. x) console. log (Object. keys (o); // => props = [] property exists, but the Object cannot be enumerated. defineProperty (o, "x", {writable: false}); // Changes attribute x to read-only o. x = 2; // An error occurred while trying to modify the value of attribute x. log (o. x); // => 1 Object. defineProperty (o, "x", {value: 2}); // However, property x is still configurable and the value feature can be directly modified. . Console. log (o. x); // => 2Object. defineProperty (o, "x", {// modify the data property to the accessor property get: function () {return 0 ;}}); console. log (o. x); // => 0

This method cannot set the attributes of the inherited attributes. You can use the Object. defineProperties () method to modify multiple attributes at the same time. The first parameter is the object to be modified. The second parameter is a ing table object that contains the attribute name and the descriptor object of the corresponding attribute.

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(this.x * this.x + this.y * this.y);    },    enumerable: true,    configurable: true  }});console.log(p.r); //=>5

7. Three attributes of the object

Prototype attributes

The prototype of an object is used to inherit attributes. This attribute is so important that "o's prototype attribute" is often called "o's prototype ".
The prototype attribute is set at the beginning of object creation. I have already introduced the prototype, but I want to add it here.

  1. Objects directly created using objects use Object. prototype as the prototype;
  2. Objects created using the new keyword use the prototype of the constructor as the prototype;
  3. Objects Created using Object. create () use the first parameter as the prototype.

In ES5, the Object is passed into the Object. getPrototypeOf () method to query its prototype Object.
To detect whether an object is a prototype of another object, use the isPrototypeOf () method.

var a = { x: 2 };var b = Object.create(a);console.log(a.isPrototypeOf(b)); //=> trueconsole.log(Object.prototype.isPrototypeOf(b));//=> true

Class attributes

The class attribute of an object is a string used to indicate the type information of the object. However, JS does not provide a direct query method. It can only be queried using one indirect method. You can call the toString () method of the object, then extract the characters from the string's 8th characters to the second-to-last position. If the toString () method inherited by the object is overwritten, the Function. call () method must be called indirectly.

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 parameters, and this function contains special processing 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

The extensible row of an object is used to indicate whether new attributes can be added to an object. In ECMAScript 5, all custom objects, built-in objects, and host objects support scalability by default. The following describes several methods for detecting and setting object scalability and their differences.

The Object. preventExtensions () method can set the passed Object to be unextensible. Note the following two points: 1. once an object is converted to an extensible one, it cannot be converted to an extensible one. 2. if you add attributes to the prototype of an unextensible object, the unextensible object will inherit these new attributes.

The Object. isExtensible () method can detect the scalability of input objects.

The Object. seal () method can set the input Object to be non-extensible, and set all its own attributes to non-configurable. That is to say, you cannot add new attributes to this object or delete or configure existing attributes. You can use the Object. isSealed () method to check whether the Object is closed.

The Object. freeze () method is more "harsh", and it will directly freeze the Object. In addition to setting the object to non-extensible and its properties to non-configurable, you can also set all data attributes of the object's own properties to read-only. You can use the Object. isFrozen () method to check whether the Object is frozen.
Object. preventExtensions (), Object. seal (), and Object. freeze () methods all return the passed Object.

8. serialize objects

I believe everyone is familiar with JSON. In fact, this section introduces JSON serialization. Serialization is the mutual conversion between JS objects and strings. JSON is used as the data exchange format. ECMAScript 5 provides two built-in functions: JSON. stringify () and JSON. parse () for serialization and restoration of JS objects.

Var obj = {x: 3, y: 5}; // define 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 "JavaScript Object Notation"-JavaScript Object Notation. The JSON syntax does not represent all values in JavaScript. Objects, NaN, array, String, infinite number, true \ false, and null can be serialized and restored. Functions, RegExp, Error objects, and undefined values cannot be serialized or restored. The JSON. stringify () function can only serialize self-owned attributes that can be enumerated by objects. The serialized date object is a date string in ISO format.

9. References and extensions

The content of this article is based on the reading summary and code practices of Chapter 6th of the JavaScript authoritative guide-object chapter. The summary is rough. You can also learn more about objects through the original work or MDN.

[1] David Flanagan, JavaScript authoritative guide (6th)
[2] MDN, JavaScript reference document-Array-JavaScript | MDN

Thank you for reading this article and hope to help you. Thank you for your support for this site!

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.