A summary of the JAVASCRIPT Advanced Programming Study VI (1)

Source: Internet
Author: User
Tags access properties function prototype hasownproperty

Introduction: We have introduced the reference type in the previous chapter, in which we probably learned about the concept of "object". It also mentions that the functions in JavaScript are objects, and even the concept of "objects of all things" can be proposed. So in this chapter I start a learning summary of JavaScript "Object", and first we can understand that object-oriented has a "class" concept. Classes can create any number of methods and objects with the same properties, but there is no concept of classes in ECMAScript. This is also a special aspect of JavaScript that differs from the general object-oriented. Object in JavaScript is an important point of knowledge, so the content of this chapter will be relatively long, summarizing aspects of the structure I will still use a sub-chapter summary, the content I try not to bias the basis of knowledge, because a lot of knowledge points I have been mentioned many times before (such as creating objects. Add attributes and so on), so it can be said that this summary of the direction will gradually become more and more non-biased basis, but slowly biased to some of the difficulties, which is what I want to do. And in some knowledge points I will try to explain through their own accumulation, as far as possible not to move the book, so whether it is to their own learning to improve or the content of the supplement is very good (in fact, I have done in the previous chapters).

Property Type:

There are two types of properties in ECMASCript: Data properties and accessor properties.

Data properties:

The Data property contains the location of a data value. Values can be read and written at this location. The data attribute has 4 attributes that describe its behavior.

1. [[[Configurable] k?n ' F?G?R?BL]: Indicates whether the property can be redefined by deleting the property, whether the attribute is modified, or whether the property can be modified to an accessor property. Properties that are defined directly on the object, as in the previous example, have the default value of true for this attribute.

2, [[Enumerable]? ' NJU:M?R?B?L]]: Indicates whether the property can be returned through the for-in loop. Properties that are defined directly on the object, as in the previous example, have the default value of true for this attribute.

3, [[[Writable] ' ra?t?b?l]: Indicates whether the value of the property can be modified. Properties that are defined directly on the object, as in the previous example, have the default value of true for this attribute.

4, [[Value] Vælju]: Contains the data value of this property. When reading a property value, read from this position, and when writing the value of the property, save the new value in this position. The default value for this attribute is undefined.

For properties defined directly on the object as in the previous example, their [[Configurable], [[]], [[writable]] attributes are set to true, and the [[Value]] attribute is set to the specified value. For example:

var person = {Name: "Nicholas"}; A property named name is created here, and the value specified for it is "Nicholas".

That is, the [[Value]] attribute will be set to "Nicholas", and any modifications to this value will be reflected in this position.

To modify the property's default attributes, you must use the ECMAScript 5 object.defineproperty () method. This method receives three parameters: the object where the property resides, the name of the property, and a descriptor object. Where the properties of the descriptor (descriptor) object must be: Configurable, enumerable, writable, and value. Set one or more of these values to modify the corresponding attribute values.

Set configurable to False to indicate that the property cannot be removed from the object. If you call delete on this property, nothing will happen in the non-strict mode and will cause an error in strict mode. Furthermore, once the attribute is defined as not configurable, it cannot be changed back to configurable. At this point, calling the Object.defineproperty () method to modify an attribute other than writable will result in an error, such as:

var person = {};

Object.defineproperty (person, "name", {

Configurable:false,

Value: "Nicholas"

}); Throw error

Object.defineproperty (person, "name", {

Configurable:true,

Value: "Nicholas"

});

The Object.defineproperty () method can be called multiple times to modify the same property, but there is a limit after setting the configurable attribute to false.

PS: When you call the Object.defineproperty () method, the default values for the configurable, enumerable, and writable attributes are false if you do not specify them. IE8 is the first browser version to implement the Object.defineproperty () method. However, the implementation of this version has many limitations: This method can only be used on DOM objects, and only accessor properties can be created. Because the implementation is not exhaustive, it is recommended that readers do not use the Object.defineproperty () method in IE8.

Accessor properties:

Accessor properties do not contain numeric values, they contain a pair of getter and setter functions (non-required functions), the Getter is responsible for reading accessor properties, and the setter is responsible for writing accessor properties. Accessor properties have the following four attributes:

1. [[[Configurable]]: Indicates whether the property can be redefined by deleting the property from Delete, can modify the attribute's attributes, or can modify the property to a data property. The default value for this attribute is true for properties that are defined directly on the object.

2, [[[Enumerable]]: Indicates whether the property can be returned through the for-in loop. The default value for this attribute is true for properties that are defined directly on the object.

3, [[Get]]: The function that is called when the property is read. The default value is undefined.

4, [[Set]]: The function that is called when the property is written. The default value is undefined.

Accessor properties cannot be defined directly and must be defined using Object.defineproperty ().

[[Configurable] and [[Enumerable]] cannot be modified in browsers that do not support the Object.defineproperty () method.

To define multiple properties:

because of the high likelihood of defining multiple properties for an object, ECMAScript 5 also defines a object.defineproperties () method. This method allows you to define multiple properties at once by using a descriptor. This method receives two object arguments: The first object is the object whose properties are to be added and modified, and the properties of the second object correspond to the property one by one to be added or modified in the first object .

Read Attribute properties:

Using the object.getownpropertydescriptor () method of ECMAScript 5, you can get a descriptor for a given property. This method receives two parameters: the object where the property resides and the name of the property whose descriptor you want to read . The return value is an object that, if it is an accessor property, has configurable, enumerable, get, and set, and if it is a data property, the properties of the object are configurable, enumerable, writable, and Value

in JavaScript, you can use the Object.getownpropertydescriptor () method for any object-including DOM and BOM objects. Browsers that support this approach are ie9+, Firefox 4+, Safari 5+, Opera 12+, and Chrome.

Prototype mode:

Each function we create has a prototype (prototype) attribute, which is a pointer to an object, and the purpose of this object is to include properties and methods that can be shared by all instances of a particular type. If it is understood literally, then prototype is the prototype object of the object instance created by invoking the constructor. The advantage of using a prototype object is that you can have all object instances share the properties and methods that it contains. In other words, instead of defining the information for an object instance in the constructor, you can add that information directly to the prototype object.

Like what:

function person () {

}

Person.prototype.name = "Nicholas";

Person.prototype.age = 29;

Person.prototype.job = "Software Engineer";

Person.prototype.sayName = function () {

alert (this.name);

};

var person1 = new Person ();

Person1.sayname (); "Nicholas"

var person2 = new Person ();

Person2.sayname (); "Nicholas"

Alert (Person1.sayname = = Person2.sayname); True

(Code Case 1)

Here we can see that we have added some properties to the object through the prototype and then created two objects for property access, all of which can be accessed to name. Here we are using prototypes to share properties and methods with objects. This is also one of the role of the prototype chain, because there is no class concept, in JavaScript so many objects will rely on the prototype for data sharing and contact.

Understanding prototype Objects:

Whenever a new function is created, a prototype property is created for the function based on a specific set of rules, which points to the prototype object of the function. By default, all prototype objects automatically get a constructor (constructor) property that contains a pointer to the function where the prototype property is located. Take the previous example, Person.prototype. constructor points to person. With this constructor, we can continue to add additional properties and methods to the prototype object. After the custom constructor is created, its prototype object will only get the constructor property by default;

Pull so much, in fact, summed up is:

From the diagram, we create a function that has a prototype attribute (prototype), then this property points to the prototype object, the prototype object contains the property we added, name age, and so on, with a constructed constructor property, This property points to the function that created the prototype object. In this way, the function is linked to the prototype object.

As for the other methods, they are inherited from Object. When the constructor is called to create a new instance, the inside of the instance contains a pointer (internal property) that points to the constructor's prototype object. ECMA-262 the 5th edition of this pointer is called [[Prototype]]. Although there is no standard way to access [[Prototype] in scripts, Firefox, Safari, and Chrome support a property __proto__ on each object, and in other implementations, this property is completely invisible to the script. However, it is really important to be clear that this connection exists between the instance and the constructor's prototype object, not between the instance and the constructor.

Look at the picture:

We have an instance of the constructor new (the JavaScript new operator pointing to the constructor) that contains a [prototype] property, where we can interpret it as __proto__ (also known as an implicit prototype, which is easy to read here), This prototype attribute also holds the function to the prototype object. In this way, you can also understand why person 1 and Person 2 can access properties in the prototype object.

Although [[Prototype]] is inaccessible in all implementations, the isPrototypeOf () method can be used to determine whether the relationship exists between objects. Essentially, if [[Prototype]] points to an object that calls the isPrototypeOf () method (Person.prototype), then this method returns True as follows:

Alert (Person.prototype.isPrototypeOf (Person1)); True

Alert (Person.prototype.isPrototypeOf (Person2)); True

ECMAScript 5 Adds a new method called Object.getprototypeof (), which returns the value of [[Prototype]] in all supported implementations. For example:

Alert (object.getprototypeof (person1) = = Person.prototype); True

Alert (object.getprototypeof (person1). Name); "Nicholas"

Using object.getprototypeof () makes it easy to get a prototype of an object, which is important in the case of using a prototype to implement inheritance (discussed later in this chapter). Browsers that support this approach are ie9+, Firefox 3.5+, Safari 5+, Opera 12+, and Chrome.

Access attribute principle: to the above example, we can access the properties in the prototype by creating Person1, because we have an implicit prototype pointing to this object when we create it, and there is a principle here: Person1 can access the prototype properties, but cannot modify the prototype properties, At the same time, if person 1 and has a property with the same name as the prototype, then person 1 accesses the property with the same name, such as the name attribute already exists in the prototype above, and the person 1.name= "Jack", Person1 also has the name property, at which person 1 accesses the Name property to access its own name property.

Use the hasownproperty () method to detect whether a property exists in an instance or exists in a prototype.

Returns False if it is from the prototype, or true if it is from an instance. For example, refer to the above: Person 1.hasOwnProperty (name)//false This attribute is derived from the prototype.

Prototypes and in operators:

There are two ways to use the In operator: use separately and in the for-in loop. When used alone, the in operator returns True when the given property is accessible through the object, whether the attribute exists in an instance or in a prototype.

Like what:

Alert ("name" in Person1); True still refers to the above (Code Case 1), where name exists in the prototype, by: When used alone, the in operator returns True when the given property is accessible through the object, whether the attribute exists in an instance or in a prototype. This returns true:

Because the in operator returns True,hasownproperty () only if the property is accessible through the object, it returns true only if the property exists in the instance, so as long as the in operator returns True and hasOwnProperty () returns false, the property can be determined is a property in the prototype.

When you use the F-or-in Loop, you return all the enumerable (enumerated) attributes that can be accessed through the object, including the attributes that exist in the instance and the properties that exist in the prototype. Instance properties that block non-enumerable properties in the prototype (properties that will be marked as false for [[Enumerable]]) are also returned in the for-in loop , because all developer-defined properties are enumerable, as defined by the Exceptions in IE8 and earlier versions. There is a bug in the implementation of earlier versions of IE that the instance properties that mask non-enumerable properties do not appear in the for-in loop. For example:

var o = {tostring:function () {

Return "My Object";

} };

For (Var prop in O) {

if (prop = = "ToString") {

Alert ("Found toString"); Not displayed in IE

} }

When the above code is running, a warning box should be displayed indicating that the ToString () method was found. The object o here defines a method named ToString () that masks the ToString (non-enumerable) method in the prototype. In IE, because its implementation considers the ToString () method of the prototype to be marked with a value of false [[Enumerable]], the property should be skipped, and we will not see the warning box. The bug affects all properties and methods that are not enumerated by default, including: hasOwnProperty (), propertyisenumerable (), tolocalestring (), toString (), and valueOf (). ECMAScript 5 also sets the [[Enumerable]] attribute of the constructor and prototype properties to false, but not all browsers follow this implementation.

To get all the enumerable instance properties on an object, you can use the Object.keys () method of ECMAScript 5. This method takes an object as a parameter and returns an array of strings containing all the enumerable properties. For example:

function person () {}

Person.prototype.name = "Nicholas";

Person.prototype.age = 29;

Person.prototype.job = "Software Engineer";

Person.prototype.sayName = function () {

alert (this.name);

};

var keys = Object.keys (Person.prototype);

alert (keys); "Name,age,job,sayname"

var p1 = new Person ();

P1.name = "Rob";

P1.age = 31;

var P1keys = Object.keys (p1);

alert (P1keys); "Name,age"

Here, the variable keys will hold an array in which the string "name", "Age", "job", and "Sayname" are in the array. This order is also the order in which they appear in the for-in loop. If it is called through an instance of person, the array returned by Object.keys () contains only two instance properties of "name" and "age". If you want to get all the instance properties, regardless of whether it is enumerable, you can use the Object.getownpropertynames () method.

var keys = object.getownpropertynames (Person.prototype);

alert (keys); "Constructor,name,age,job,sayname"

Note The constructor attribute is included in the results. Both the Object.keys () and Object.getownpropertynames () methods can be used to replace the for-in loop. Browsers that support both methods are ie9+, Firefox 4+, Safari 5+, Opera 12+, and Chrome.

--------------------------------------------------------------------------------the end of this chapter------------------------------------- --------------------------------------------------------------------------------------------------------------- ---------

Next: Continue the learning summary of the prototype in the object, including the implementation of the inheritance, and so on to the general knowledge points.

This chapter I draw a picture, in fact, in the book is similar to the picture, but I personally feel that the picture in the book is very uncomfortable to understand, looking at a very messy, on their own (soul convey) drew two, cough cough, painting is not very good-looking.

This chapter is mainly about the prototype has a general understanding of what the prototype is, what is the use of prototypes? Including the fact that we may have seen _prototype_ (display prototypes) and _proto_ (implicit prototypes) in other materials, it is necessary to say that different data are represented differently, but the blame is summed up, the meaning is the same, one is the function prototype, One is the instance object prototype. We should not be confused by too much information when we study, in fact they want to express the same.

A summary of the JAVASCRIPT Advanced Programming Study VI (1)

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.