02. Inheritance in JavaScript -- inherits

Source: Internet
Author: User

 

02. Inheritance in Javascript ---- inherits

This article does not elaborate too much on the concept of inheritance in OOP, but uses native JavaScript code to simulate class inheritance (not object extension)

Class inheritance: inherits

Assume that a defined superclass (parent class) superclass and a subclass to be inherited exist. Therefore, you can define the following methods to implement class inheritance:

Inherits method definition

For the following inherits method, see Pro JavaScript design patterns [Ross harmes and Dustin Diaz]

/*** This method is used to implement class inheritance * @ Param {function} subclass to be inherited * @ Param {function} superclass parent class to be inherited * @ exception {error} if the parameter is invalid, an exception is thrown */var inherits = function (subclass, superclass) {If (arguments. length! = 2) {Throw new error ("subclass and parent class must be explicitly specified");} For (VAR I = 0, n = arguments. length; I <n; I ++) {If (typeof arguments [I]! = "Function") {Throw new errorr ("both the subclass and parent class must be function") ;}} var F = function () {}; F. prototype = superclass. prototype; subclass. prototype = new F (); subclass. prototype. constructor = subclass ;};

The method performs a strict parameter validity check internally. The parameter must be of two types: a subclass and a parent class. In addition, both parameters must be of the function type. Otherwise, an exception is thrown, declaring inheritance failed

Step 1 of using the inherits Method
/*** Define parent class */var superclass = function () {}; superclass. prototype = {name: "Zhao xianlie", talk: function () {alert ("My name is" + this. name) ;}};/*** define subclass here */var subclass = function () {}; // implement inheritance of inherits (subclass, superclass ); // create a subclass and call the method inherited from the subclass var osub = new subclass (); osub. talk (); // output here: My name is Zhao xianlie

From the execution results of the program, we can see that this inheritance method copies all the content of the parent class (except the constructor) to the subclass, successfully completing the class inheritance.

Step 2
/*** Define the parent class */var superclass = function () {This. name = "Zhao xianlie"; this. talk = function () {alert ("My name is" + this. name) ;};};/*** define the subclass here */var subclass = function () {// this is an empty class}; // implement the inheritance of inherits (subclass, superclass); // create a subclass object and call the method var osub = new subclass () inherited from the parent class; osub. talk (); // according to the concept of inheritance, the output here should be: My name is Zhao xianlie

After the program is actually executed, an exception occurs. cause: the talk method does not exist in the osub instance. Isn't it inherited through the inherits method? Why doesn't this happen?
How? The reason is that, within the inherits, the prototype chain of the superclass is copied to subclass, instead of superclass.
The attributes and methods in the prototype chain cannot be obtained by the subclass.

To support both the first inheritance and the second inheritance, we can only upgrade the inherits method again and change it to the following form:

/*** This method is used to implement class inheritance * @ Param {function} subclass to be inherited * @ Param {function} superclass parent class to be inherited * @ exception {error} if the parameter is invalid, an exception is thrown */var inherits = function (subclass, superclass) {If (arguments. length! = 2) {Throw new error ("subclass and parent class must be explicitly specified");} For (VAR I = 0, n = arguments. length; I <n; I ++) {If (typeof arguments [I]! = "Function") {Throw new errorr ("both the subclass and parent class must be function");} subclass. prototype = new superclass (); subclass. prototype. constructor = subclass ;};

After such changes, the situation in step 1 and Step 2 can be smoothly executed.

Step 3

If the subclass. prototype in the Code is changed to the following form based on Step 2:

Subclass. prototype = {walk: function () {alert ("Even so, I can walk") ;}, talk: function () {alert ("My name is not" + this. name );}

};

Run the following code:

Inherits (subclass, superclass); var osub = new subclass (); osub. talk (); // here the output is still: My name is Zhao xianlie // The key is in the following osub. walk (); // an exception is thrown here, telling us that the walk method does not exist.

After analyzing this result, the output of osub. Talk () should be: My name is not Zhao xianlie. In addition, osub. Walk () should have output, and the program should be executed normally. But why is there such a running result?

Why? I believe you have long known that there is such a key code in the inherits method:

subClass.prototype = new superClass();

We have already told you that the prototype chain in the subclass has been completely replaced. In fact, this is a violation of the inheritance principle (generally, not all subclasses cover the parent class? Why
In turn ).

However, we have to solve such a problem. We must ensure that the so-called inheritance can meet the above three conditions at the same time. After meditation, I decided to change it to this:

/*** This method is used to implement class inheritance * @ Param {function} subclass to be inherited * @ Param {function} superclass parent class to be inherited * @ exception {error} if the parameter is invalid, an exception is thrown */var inherits = function (subclass, superclass) {If (arguments. length! = 2) {Throw new error ("subclass and parent class must be explicitly specified");} For (VAR I = 0, n = arguments. length; I <n; I ++) {If (typeof arguments [I]! = "Function") {Throw new errorr ("both the subclass and parent class must be function") ;}} var osuper = new superclass (); for (var key in osuper) {If (! Subclass. Prototype [Key]) {subclass. Prototype [Key] = osuper [Key] ;}} subclass. Prototype. constructor = subclass ;};

OK. Through this upgrade, the above Code is run again and the process passes smoothly.

The inherits method, which has been upgraded twice, is also a relatively stable version. This is the inherits method mentioned in subsequent articles.

This article aims to discuss the inheritance of classes in Javascript. It is only one of the simulation methods. We apologize for improper simulation.

You are welcome to provide valuable upgrade suggestions.

 

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.