"JavaScript Advanced Programming Notes" chapter sixth OOP

Source: Internet
Author: User
Tags hasownproperty

Busy for a period of time, add nearly one months of the class. The book also fell not to see, the last to see the seventh chapter (this part of the note is probably the September bar), occasionally see very laborious. Watch the speed slow down.

Learning is a process of slowly accumulating and settling slowly. There was no apparent improvement in reading. But after reading the book in the near period of time to write code, obviously feel efficiency or improve, the basic knowledge is solid.

This book is the second time to see, this time very seriously read and take notes, notes of the text are their own side to see the knock, so that the better real absorption to a part of it!

These days are looking at web responsive design: HTML5 and CSS3 Combat

The 6th chapter is about the design of 6.1.1 property types for image

There are two properties in ECMAScript: Data Sex and accessor properties.

1. 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.

[[Configurable]]: Indicates whether the property can be redefined by deleting the property from the delete. Can you modify the attributes of a property, or can you modify the property to an accessor property. Properties that are defined directly on the object as in the previous example, the default value of which is true.

[[Enumerable]]: Indicates whether the property can be returned through a for-in loop. Define properties directly on the object as in the previous example, and their default value is true.

[[writable]]: Indicates whether the value of the property can be modified, as in the previous example, the property is defined directly on the object, the default value True

[[Value]]: Contains the data value for this property. When reading a property value, the new value is stored in this position when the property value is read from this location. Default is undefined

The attributes to be modified must use the

Object.defineproperty ()

This method receives three parameters: the object where the property resides, the name of the property, and a descriptor object.

The property of the descriptor (descriptor) object must be: Configurable,enumerable,writable,value

Set one or more of these values to modify the corresponding attribute values.

2. Accessor Properties

[[Configurable]]: Indicates whether the property can be redefined by deleting the property from the delete. Can you modify the attributes of a property, or can you modify the property to a data property. For properties that are defined directly on the object, the default value of this property is true.

[[Enumerable]]: Indicates whether the value of the property can be modified, as in the previous example, the property is defined directly on the object, the default value True

[[Get]]: The function that is called when the property is read. Default undefined

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

Accessor properties cannot be defined directly, you must use Object.defineproperty () to define

6.1.2 Defining multiple properties

Because there is a high likelihood of defining multiple properties for an object.

ECMAScript 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 second object's properties are corresponding to the property one by one to be added or modified in the first object.

6.1.3 Properties of Read attributes

The Object.getownpropertydescriptor () method can obtain a descriptor for a given property.

This method receives two parameters: the object where the property resides and the name of the property to read its description. The return value is an object.

In JavaScript you can use the Object.getownpropertydescriptor () method on any object, including the Dom BOM.

6.2 Creating Objects 6.2.1 Factory mode

function Creatperson (name,age,job) {

var o = new Object ();

O.name = name;

O.age = age;

O.job = job;

O.sayname = function () {

alert (this.name);

}

}

Var Person1 = Creatperson ("Wang", "Web Front End")

var person2 = Creatperson ("Lee", "Java Development")

6.2.2 Constructor Mode

function Person (name,age,job) {

THIS.name = name;

This.age = age;

This.job = job;

This.sayname = Funciont () {

Alert (this.name)

}

}

var person1 = new Person ("Wang", "Web Front End")

var person2 = new Person ("Lee", "Java Development")

Although the constructor pattern is useful, it is not without its drawbacks, the main problem with constructors is that each method is recreated on each instance.

In the previous example, Person1,person2 has a method named Sayname (), but two methods are not an instance of the same function. The functions in ECMAScript are objects, so each defines a function, that is, instantiating an object.

It is not necessary to create two function instances to accomplish the same task, and there is this object that, without having to bind the function to a particular object before executing the code, you can solve the problem by moving the function definition outside the constructor.

function Person (name,age,job) {

THIS.name = name;

This.age = age;

This.job = job;

This.sayname = Sayname;

}

function Sayname () {

alert (this.name);

}

var person1 = new Person ("Wang", "Web Front End")

var person2 = new Person ("Lee", "Java Development")

6.2.3 Prototype mode

function person () {}

Person.prototype.name = "Wang";

Person.prototype.age = 27;

Person.prototype.job = "web";

Person.prototype.sayName = function () {

Alert (this.name);

}

var person1 = new Person ();

Peson1.sayname ()//wang

1. 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.

Use the hasOwnProperty () method to detect whether a property exists in an instance or exists in a prototype. This method returns true only if the given property exists in the object instance. New is all examples.

2. Prototypes and in operators

There are two ways to use the In operator, use it alone, and use it in a 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.

Using both the hasOwnProperty () and the In operator, you can determine whether the property exists in the object or is in a prototype.

When you use the for-in loop, you return all the enumerable (enumerabted) properties 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 mask non-enumerable properties in the prototype are also returned in the for-in loop because all developer-defined properties are enumerable (except IE8), as required.

Object.keys () method. Takes an object as a parameter and returns an array of strings containing all the enumerable properties.

The result contains a non-enumerable constructor property. Both the Object.kyes () and Object.getownpropertynames () methods can be used to replace the for-in loop.

3. Simpler prototype syntax

In the previous example, every attribute and method is added to Person.prototype. To reduce unnecessary input and visually better encapsulate prototype functionality, it is more common to rewrite the entire prototype object with an object literal that contains all the properties and methods.

Function person () {}

Person.prototype = {

Name: "Wang",

Age:27,

Job: "Web",

Sayname:function () {

alert (this.name);

}

}

In the preceding code, Person.prototype is set to equal to a new object created as an object literal. The end result is the same, with one exception: the constructor property no longer points to person. As mentioned earlier, each time a function is created, its prototype object is created, and the object automatically obtains the constructor property. In essence, the default prototype object is completely overridden by using the words above. So the constructor property also becomes the new object constructor property (pointing to the object constructor) no longer points to the person function. Although the instanceof operator can return the correct result. However, the type of the object cannot be determined by constructor. If the constructor property is important, you can deliberately set it to the appropriate value as follows.

Function person () {}

Person.prototype = {

constructor: "Person",

Name: "Wang",

Age:27,

Job: "Web",

Sayname:function () {

alert (this.name);

}

}

Resetting the constructor property in this manner causes the [[enumerable]] property to be set to true, and the native constructor property is not enumerable by default.

4. The dynamic nature of the prototype

5. prototype of native object

The importance of prototype patterns is not only in the creation of custom types, but even in all native reference types, which are created using this pattern. All native reference types (array,object,string, and so on) are defined as methods on the prototype of their constructors. For example, the sort () method can be found in array.prototype, and the substring method can be found in String.prototype.

Through the prototype of the native object, you can not only get references to all the default methods, but also define new methods.

6. problems with prototype objects

Prototyping mode is also not without drawbacks.

First, it omits the process of passing initialization parameters to the constructor, resulting in all instances getting the same property value by default. While this will somehow bring some inconvenience, this is not the biggest problem with prototypes. The biggest problem with prototype mode is that it is caused by its shared nature.

All the properties in the prototype are shared by many instances, and this kind of sharing is appropriate for the function. For those attributes that contain basic values, the past is also said, after all, by adding a property of the same name on the instance, you can hide the corresponding property in the prototype, however, for attributes that contain reference type values, the problem is more prominent.

6.2.4 combination using constructor mode and prototype mode

The most common way to create a custom type is to combine the constructor pattern with the prototype pattern. The constructor pattern is used to define instance properties, and the prototype schema is used to define methods and shared properties. As a result, each instance will have its own copy of the instance properties, but it also shares a reference to the method. Maximum savings in memory.

This is a default pattern for defining reference types.

6.2.4 combination using constructor mode and prototype mode

6.2.5 Parasitic structural function pattern

The basic idea of this pattern is to create a function that simply encapsulates the code that creates the object, and then returns the newly created object, but on the surface. This function is much like a typical constructor.

function Creatperson (name,age,job) {

var o = new Object ();

O.name = name;

O.age = age;

O.job = job;

O.sayname = function () {

alert (this.name);

return o;

}

6.3 Inheritance

ECMAScript only supports implementation of inheritance, and its implementation is mainly based on the prototype chain implementation.

6.3.1 prototype chain

1. Don't forget the default prototype

All reference types inherit object by default, and this continues to be done through the prototype chain. Keep in mind that the default prototype for all functions is an instance of object, so the default prototype will contain an internal pointer to Object.prototype. This is exactly the root cause of the default methods, such as ToString () \valueof (), which the custom type will continue.

2. Determining the relationship between prototypes and instances

There are two ways to determine the relationship between a prototype and an instance.

The first approach is to pass the instanceof operator, which will return true if the instance and the constructor in the prototype chain have been tested with this operator.

Instance instanceof Object//true

Box two way is to use the isprototypeof () method, with the same, as long as the prototype chain appears in the prototype, can be said that the prototype chain derived from the prototype, so the isPrototypeOf () method will also return true;

Object.prototy.isPrototypeOf (instance)//true;

3. Prudent method of definition

Subtypes sometimes need to rewrite a method in a superclass, or you need to add a method that does not exist in the super type. However, the code that adds a method to the prototype must be placed after the statement that replaced the prototype.

Function supertype () {

This.property = true;

}

SuperType.prototype.getSuperValue = function () {

Return This.property;

}

Function subtype () {

This.subproperty= false;

}

Inherited the supertype.

Subtype.prototype = new Supertype ();

// Add a new method

Subtype.prototype.getsubvalue = function () {

Return This.subproperty;

};

// overriding methods in super-types

Subtype.prototype.getsupervalue = function () {

Return false;

}

Var instance = new Subtype ();

Instance.getsupervalue ()//false

In the above code, the bold part is the definition of two methods.

Also, you cannot use object literals to create a prototype method when you implement inheritance through a prototype chain. Because doing so will rewrite the prototype chain.

4. Problems with the prototype chain

Although the prototype chain is very powerful, it can be used to implement inheritance, it also has some problems.

The main problem comes from prototypes that contain reference type values. The prototype properties that we've described earlier that contain reference type values are shared by all instances, and that's why you define properties in the constructor, not in the prototype object. When you implement inheritance through a prototype, the prototype will actually become an instance of another type. As a result, the original instance attributes have naturally become the archetypal attributes of the present.

The second problem with the prototype chain is that when you create an instance of a subtype, you cannot pass parameters to the super-type constructor. In fact, it should be said that there is no way to pass parameters to a super-type constructor without affecting all object instances: The prototype chain is seldom used alone in practice because of the problems with the reference type values in the prototype.

6.3.2 Borrowing constructors

In the process of solving the problem of containing reference type values in the prototype, the developer began using a technique called borrowing constructors (sometimes called objects or classic inheritance). The basic idea of this technique is quite simple, which is to call the superclass constructor inside the sub-type constructor. Remember, a function is simply an object that executes code in a particular environment, because you can also execute a constructor on a newly created object by using the Apply () and call () methods.

Function supertype () {

This.colors = ["Red", "Blue", "green"];

Function subtype () {

// inherited the supertype.

Supertype.call (this);

}

Var Instance1 = new Supertype ();

Instance1.colors.push ("Black");

Instance1.colors//"Red,blue,green,black"

Var Instance2 = new subtype ();

Instance2.colors//"Red,blue,green"

The code's bold line of Code "seconded" the super-type constructor, and by using the call method (or the Apply () method), we actually called the Supertype constructor in the context of the newly created subtype instance. In this way, all the object initialization code defined in the Supertype () function is executed on the new subtype. As a result, the first instance of subtype will have its own copy of the Colors property.

1. passing Parameters

function Supertype (name) {THIS.name =name}

Function subtype () {Supertype.call (this, "Wang"); this.age = 28;}

var inst = new Subtype ()

When the Supertype constructor is called inside the subtype constructor, the Name property is actually set for the instance of subtype. To ensure that the Supertype constructor does not override the subtype's sexual nature. You can add a defined property that should be in a subtype after the superclass type constructor.

2. questions about borrowing constructors

If you simply borrow a constructor, you will not be able to avoid the problem with the constructor pattern--methods are defined in the constructor, so the use of the function is impossible to discuss. Also, the method defined in the super-type prototype is not visible to the subtype. The result is that all types can only use the constructor pattern. Taking into account these problems, borrow.

6.3.3 Combination Inheritance

Combinatorial inheritance, sometimes called pseudo-classical inheritance, refers to the combination of the prototype chain and the technique of borrowing the constructor into one piece, thus exerting a succession pattern of both. The idea behind it is to use the prototype chain to implement the inheritance of the prototype properties and methods, and to implement the inheritance of the attributes through the constructor function.

Combined inheritance avoids the defects of the prototype chain borrowing constructors, integrates their advantages and becomes the most common inheritance mode of JavaScript. Furthermore, instanceof and isprototypeof () can also be used to identify objects that are created based on composite inheritance.

6.3.4-Prototype inheritance

This approach does not use a strictly constructed constructor. His idea was to use prototypes to create new objects based on existing objects without having to create custom types.

Function Object (o) {

Function f () {}

P.ptototype = O;

return new F ();

}

6.3.5 Parasitic Inheritance

Waiting to be mended

"JavaScript Advanced Programming Notes" chapter sixth OOP

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.