Summary of the six modes inherited by javascript and six in javascript

Source: Internet
Author: User

Summary of the six modes inherited by javascript and six in javascript

1. prototype chain

Function SuperType () {this. property = true;} SuperType. prototype. getSuperValue = function () {return this. property ;}; function SubType () {this. subproperty = false;} // inherits the SuperTypeSubType. prototype = new SuperType (); SubType. prototype. getSubValue = function () {return this. subproperty;}; var instance = new SubType (); alert (instance. getSuperValue (); // true

The essence of implementation is to override the prototype object and replace it with a new type of instance.

2. Borrow Constructors

Function SuperType () {this. colors = ["red", "blue", "green"];} function SubType () {// inherits the SuperTypeSuperType. call (this);} var instance1 = new SubType (); instance1.colors. push ("black"); alert (instance1.colors); // "red, blue, green, black" var instance2 = new SubType (); alert (instance2.colors ); // "red, blue, green"

If only the constructor is used, the constructor mode cannot be avoided. methods are defined in constructor, so function reuse is impossible. In addition, the methods defined in the super-type prototype are invisible to sub-types, and only the constructor mode can be used for all types of results. Considering these issues, the techniques for borrowing constructors are rarely used independently.

3. Combined inheritance

Function SuperType (name) {this. name = name; this. colors = ["red", "blue", "green"];} SuperType. prototype. sayName = function () {alert (this. name) ;}; function SubType (name, age) {// inherits the SuperType attribute. call (this, name); this. age = age;} // Inheritance Method SubType. prototype = new SuperType (); SubType. prototype. constructor = SubType; SubType. prototype. sayAge = function () {alert (this. age) ;}; var instance1 = new SubType ("Nicolas", 29); instance1.colors. push ("black"); alert (instance1.colors); // "red, blue, green, black" instance1.sayName (); // "Nicolas"; instance1.sayAge (); // 29var instance2 = new SubType ("Greg", 27); alert (instance2.colors); // "red, blue, green" instance2.sayName (); // "Greg "; instance2.sayAge (); // 27

In this example, the SuperType constructor defines two attributes: name and colors. The prototype of SuperType defines a method sayName (). The SubType constructor imports the name parameter when calling the SuperType constructor, and then defines its own attribute age. Then, assign the SuperType instance to the SubType prototype, and then define the method sayAge () on the new prototype (). In this way, two different SubType instances can have their own attributes, including the colors attributes, and the same method can be used.

Combination inheritance avoids the defects of prototype chain and borrow constructor, integrates their advantages, and becomes the most common inheritance mode in JavaScript. In addition, instanceof and isPrototypeOf () can also be used to identify objects created based on combination inheritance.

4. Original Type inheritance

function object(o){function F(){}F.prototype = o;return new F();}

Within the object () function, a temporary constructor is created, the input object is used as the prototype of the constructor, and a new instance of this temporary type is returned. In essence, an object () performs a shortest copy on the objects that are passed in. Let's look at the example below.

var person = {name: "Nicholas",friends: ["Shelby", "Court", "Van"]};var anotherPerson = object(person);anotherPerson.name = "Greg";anotherPerson.friends.push("Rob");var yetAnotherPerson = object(person);yetAnotherPerson.name = "Linda";yetAnotherPerson.friends.push("Barbie");alert(person.friends); //"Shelby,Court,Van,Rob,Barbie"

The original type inheritance proposed by croford requires that you have to have an object as the basis of another object. If such an object exists, you can pass it to the object () function, and then modify the object as needed. In this example, the person object can be used as another object, so we pass it into the object () function, and then the function returns a new object. This new object uses person as the prototype, so its prototype contains a basic type Value Attribute and a reference type value attribute. This means that person. friends not only belongs to person, but also will be shared by anotherPerson and yetAnotherPerson. In fact, this is equivalent to creating two copies of the person object.

ECMAScript 5 standardizes the original type inheritance by adding the Object. create () method. This method receives two parameters: an object used as the new object prototype and (optional) an object that defines additional attributes for the new object. When a parameter is input, Object. create () and object () Methods behave the same.

var person = {name: "Nicholas",friends: ["Shelby", "Court", "Van"]};var anotherPerson = Object.create(person);anotherPerson.name = "Greg";anotherPerson.friends.push("Rob");var yetAnotherPerson = Object.create(person);yetAnotherPerson.name = "Linda";yetAnotherPerson.friends.push("Barbie");alert(person.friends); //"Shelby,Court,Van,Rob,Barbie"

The second parameter of the Object. create () method is in the same format as the second parameter of the Object. defineProperties () method: Each attribute is defined by its own descriptor. Any attribute specified in this way will overwrite the attributes of the same name on the prototype object. For example:

var person = {name: "Nicholas",friends: ["Shelby", "Court", "Van"]};var anotherPerson = Object.create(person, {name: {value: "Greg"}});alert(anotherPerson.name); //"Greg"

Browsers that support the Object. create () method include IE9 +, Firefox 4 +, Safari 5 +, Opera 12 +, and Chrome.

It is not necessary to create constructors in a crowd, but to keep an object similar to another, the original type inheritance is fully competent. But don't forget that all attributes that contain reference type values always share the corresponding values, just like using the prototype mode.

5. Parasitic inheritance

Parasitic inheritance is closely related to the original type inheritance, and is also extended by croford. The concept of parasitic inheritance is similar to that of parasitic constructor and factory mode, that is, to create a function that is only used to encapsulate the inheritance process. This function internally enhances the object in some way, finally, it returns the object just as it does all the work. The following code demonstrates the parasitic inheritance mode.

Function createAnother (original) {var clone = object (original); // create a new object clone by calling the function. sayHi = function () {// enhance this object in some way alert ("hi") ;}; return clone; // return this object}

In this example, the createAnother () function receives a parameter, that is, the object to be used as the base of the new object. Then, pass this object (original) to the object () function and assign the returned result to clone. Add a new method sayHi () for the clone object and return the clone object. You can use the createAnother () function as follows:

var person = {name: "Nicholas",friends: ["Shelby", "Court", "Van"]};var anotherPerson = createAnother(person);anotherPerson.sayHi(); //"hi"

In this example, the code returns a new object named anotherPerson Based on person. The new object not only has all attributes and methods of person, but also has its own sayHi () method.
Parasitic inheritance is also a useful mode when you consider objects rather than custom types and constructors. The object () function used in the inheritance mode is not required. Any function that can return new objects applies to this mode.

Adding a function to an object using parasitic inheritance will reduce the efficiency of function reuse.
Point is similar to the constructor mode.

6. Parasitic combined inheritance

As mentioned above, combined inheritance is the most common inheritance mode in JavaScript. However, it also has its own shortcomings. The biggest problem with combination inheritance is that, under any circumstances, super-Type constructor is called twice: one is within the sub-Type constructor when the sub-type prototype is created, and the other is within the sub-Type constructor. Yes, the child type will eventually contain all the instance attributes of the super type object, but we have to override these attributes when calling the child Type constructor. Let's take a look at the example of combined inheritance below.

Function SuperType (name) {this. name = name; this. colors = ["red", "blue", "green"];} SuperType. prototype. sayName = function () {alert (this. name) ;}; function SubType (name, age) {SuperType. call (this, name); // The second call of SuperType () this. age = age;} SubType. prototype = new SuperType (); // call SuperType () SubType for the first time. prototype. constructor = SubType; SubType. prototype. sayAge = function () {alert (this. age );};

The line in bold is the code that calls the SuperType constructor. When the SuperType constructor is called for the first time, SubType. prototype will obtain two attributes: name and colors. They are both SuperType instance attributes, but are now in the SubType prototype. When the SubType constructor is called, The SuperType constructor is called again. This time, the instance property name and colors are created on the new object. Therefore, these two attributes shield the two attributes with the same name in the prototype. Figure 6-6 shows the preceding process.
As shown in Figure 6-6, there are two groups of name and colors attributes: one group on the instance and the other in the SubType prototype. This is the result of calling the SuperType constructor twice. Fortunately, we have found a solution to this problem-parasitic combined inheritance.

The so-called parasitic combined Inheritance refers to the inheritance of attributes by using constructors and the inheritance of methods through the mixed form of prototype chains. The basic idea behind it is: We don't have to call a super-Type constructor to specify the sub-type prototype. What we need is nothing more than a copy of the super-type prototype. Essentially, it is to use parasitic inheritance to inherit the super-type prototype and then specify the result to the sub-type prototype. The basic mode of parasitic combined inheritance is as follows.

Function inheritPrototype (subType, superType) {var prototype = object (superType. prototype); // create the prototype object. constructor = subType; // enhancement object subType. prototype = prototype; // specifies the object}

In this example, the inheritPrototype () function implements the simplest form of parasitic combined inheritance. This function receives two parameters: subtype constructor and subtype constructor. In the function, the first step is to create a copy of the super-type prototype. The second step is to add the constructor attribute to the created copy to compensate for the default constructor attribute lost due to the prototype rewriting. In the last step, assign the newly created object (that is, the copy) to the sub-type prototype. In this way, we can use the statement that calls the inherit-Prototype () function to replace the statements in the previous example that assign values to the child Type Prototype. For example

function SuperType(name){this.name = name;this.colors = ["red", "blue", "green"];}SuperType.prototype.sayName = function(){alert(this.name);};function SubType(name, age){SuperType.call(this, name);this.age = age;}inheritPrototype(SubType, SuperType);SubType.prototype.sayAge = function(){alert(this.age);};

The efficiency in this example is that it only calls a SuperType constructor once, and thus avoids creating unnecessary and redundant attributes on SubType. prototype. At the same time, the prototype chain can remain unchanged; therefore, instanceof and isPrototypeOf () can be used normally (). Developers generally think that parasitic combined inheritance is the ideal inheritance paradigm of the reference type.

The YAHOO. lang. extend () method of YUI adopts parasitic combination inheritance, which makes this mode appear in a very extensive JavaScript library for the first time. For more information about YUI, visit http: // developer. yahoo.com/yui /.

The above is all the content of this article. I hope it will help you learn javascript inheritance.

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.