Simple-inheritance source code analysis _ Javascript skills

Source: Internet
Author: User
The Javascript language is not good for inheritance implementation. Engineers need to implement a complete Inheritance Mechanism on their own. The following is a simple and profound understanding of how to use javascript inheritance. If you are interested in javascript inheritance, let's take a look at the common questions. Most people may not be able to understand them systematically. The Javascript language is not good for inheritance implementation. Engineers need to implement a complete Inheritance Mechanism on their own. The following describes how to use javascript inheritance in a simple and in-depth system.

1. directly use the prototype chain

This is the simplest and most crude method, and cannot be used in a specific project. A simple demo is as follows:

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

The problem with this method is that the attributes in the prototype are shared by the instances used. Changing an inherited attribute through an instance affects other instances ., This is obviously not a general inheritance.

2. Use constructors

A constructor is essentially just a function. It can be called in any scope. A simple inheritance can be implemented by calling a parent constructor in a sub-constructor.

function SuperType(){  this.colors = {"red","blue","green"}}function SubType(){  SuperType.call(this);  }var instance = new SubType();

This implementation avoids the attribute sharing of multiple instances, but introduces new problems, such as the inability to share functions, and the instance instanceof SuperType is false.

3. Combined use of prototype and constructor

function SuperType(name){  this.name = name;  this.colors = {"red","blue","green"}}SuperType.prototype.sayName = function(){  //code}function SubType(name,age){  SuperType.call(this,name);   this.age = age;}SubType.prototype = new SuperType();var instance = new SubType();

The combination of prototype and constructor is the most common inheritance mode in javascript. In this way, each instance has its own attributes and can share the methods in the prototype. However, the disadvantage of this method is that, in any case, two superclass constructor calls will be performed. One is when the subclass prototype is created, and the other is inside the subclass constructor. How can this problem be solved?

4. Parasitic combined inheritance

The prototype of SubType is not necessarily a SuperType instance. It only needs to be a normal object of a constructor prototype that is a SuperType prototype. The Douglas Crockford method is as follows:

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

In fact, this is the implementation of Object. create in ES5. We can modify the 3rd solutions in this article:

function inheritPrototype(subType,superType){  var prototype = object(superType.prototype);  prototype.constructor = subType;  subType.prototype = prototype;}function SuperType(name){  this.name = name;  this.colors = {"red","blue","green"}}SuperType.prototype.sayName = function(){  //code}function SubType(name,age){  SuperType.call(this,name);   this.age = age;}inheritPrototype(SubType,SuperType);var instance = new SubTYpe();

In fact, parasitic combined inheritance is already a very good inheritance implementation mechanism, enough to cope with daily use. If we put forward a higher requirement: for example, how to call the method of the parent class in the subclass?

5. Implementation of simple-inheritance Library

I refused to read such obscure code at first, but I found that Daniel was a great guy, and his exquisite ideas were everywhere. I have detailed comments on each line of code. If you want to know the details, please be sure to study in detail and read each line. I think the most subtle thing about this implementation is to rewrite the parent class method as needed. In the instance object, you can use _ super to call the method of the same name as the parent class, similar to the implementation of java.

(Function () {// initializing is used to control class initialization. It is very clever. Please note the following tips: // fnTest returns a regular expression to check whether the function contains _ super, in this way, rewrite as needed to improve efficiency. Of course, if the browser does not support it, it will return a General Regular Expression var initializing = false, fnTest =/xyz/. test (function () {xyz ;})? /\ B _super \ B /:/. * // The base Class of all classes. here this is generally the window object this. class = function () {}; // Add the extend Method to the base Class to inherit the Class from the base Class. extend = function (prop) {// Save the prototype var _ super = this of the current class. prototype; // create the object of the current class, which is used to assign a value to the prototype of the subclass. Here, the parent class instance is cleverly used as the prototype of the subclass, it also avoids the initialization of the parent class (through the initializing control of the closure scope) initializing = true; var prototype = new this (); initializing = false; // assign a value to prototype in the prop parameter. The prop here generally includes the object of the init function and other functions for (var name in Prop) {// corresponding to the cognominal function, which requires special processing. After processing, you can use this in the subfunction. _ super () calls the constructor of the parent class with the same name. The fnTest here is clever: only when _ super is contained in the subclass can the data be written to improve efficiency. prototype [name] = typeof prop [name] = "function" & typeof _ super [name] = "function" & fnTest. test (prop [name])? (Function (name, fn) {return function () {// _ super here is our keyword. You need to temporarily store var tmp = this. _ super; // you can use this. _ super calls the constructor of the parent class. _ super = _ super [name]; // call the subclass function fn. apply (this, arguments); // restore _ super. If tmp is empty, you do not need to restore tmp & (this. _ super = tmp) ;}} (name, prop [name]): prop [name] ;}// when an object is new, actually, the init Method on this type of prototype is called. Note that the parameters passed through the new call must correspond one to one with the parameters of the init function. function Class () {if (! Initializing & this. init) {this. init. apply (this, arguments) ;}// set the prototype Class for the subclass. prototype = prototype; // set the constructor Class for the subclass. prototype. constructor = Class; // sets the extend method of the subclass so that the subclass can be inherited by the extend method. extend = arguments. callee; return Class ;}})();

By using the simple-inheritance library, we can implement inheritance in a simple way. Do we find that inheritance is especially similar to that of a strong language.

var Human = Class.extend({ init: function(age,name){  this.age = age;  this.name = name; }, say: function(){  console.log("I am a human"); }});var Man = Human.extend({  init: function(age,name,height){    this._super(age,name);    this.height = height;  },   say: function(){    this._super();    console.log("I am a man");   }});var man = new Man(21,'bob','191');man.say();

I will explain the Javascript inheritance Mechanism and simple-inheritance source code analysis in a simple way. I hope this article will help you.

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.