Inheritance usage in JavaScript

Source: Internet
Author: User

This article summarizes JavaScript's use of inheritance, and hopefully this article will help you with JavaScript programming. Share to everyone for your reference. Specific as follows:
The code is as follows:

/** * Implements subclasses to inherit parent class, but does not produce extra properties and methods * @returns {Function}*/define (function () {returnfunction (subtype, supertype) {varProto =NewObject (supertype.prototype);p roto.constructor=Subtype;subtype.prototype=Proto;}; });//——————————————————————————define (function () {function ostring (s) { This. str =s; This. length = This. Str.length;} Ostring.prototype.show=function () {alert ( This. str);};returnostring;});//——————————————————————————Define (['Inherit','ostring'], function (Inherit, ostring) {function wstring (s) {//calling the parent class constructor with call implementationOstring.call ( This, s); This. Chlength =2*s.length;}//Inherit other propertiesInherit (wstring, ostring); Wstring.prototype.add=function (w) {alert ( This. STR +w);};returnwstring;});
First, using function to achieve:
function Person (name) { This. Name =name;} Person.prototype.getName=function () {return  This. Name; function Author (name, books) { This. inherit=Person ;  This. Inherit (name);  This. Books =Books; }varau=NewAuthor ("Dororo","Learn much"); Au.name

or equally valid:

 function person (name) { this . Name =  name; Person.prototype.getName  = function () {  this  .name;} function Author (name, books) {Person.call ( this  , name);     this . Books = books;  var  au=new  Author ( " dororo  " ,  learn much  "   

Because this is simply the constructor of the parent class person that is called this as a parameter, all domains that are assigned to the parent class are assigned to the author subclass, so any defined domain (prototype prototype) other than the parent class person constructor, the subclass does not inherit. So in the above example, Au.getname will not be defined (undefined), because getname is defined in the person's prototype object.

Also, the subclass's constructor calls the parent class constructor before defining its own domain, so that the definition of the subclass is overridden by the parent class. That is, author defines the property book to be overwritten after person.call, otherwise it is overridden by a property in person. At the same time, it is also better not to use prototype to define the function domain of subclasses in subclasses, because after a subclass is new, it executes prototype after instantiation, and then the constructor of the parent class is called, which is also easily overridden by the properties of the parent class.

Second, realize with prototype:
function Person (name) { This. Name =name;} Person.prototype.getName=function () {return  This. Name; function Author (name, books) { This. Books =Books; }author.prototype=NewPerson (name); Author.prototype.constructor=Author; Author.prototype.getBooks=function () {return  This. Books;}varau1=NewAuthor ("Dororo1","Learn much");varAu2=NewAuthor ("Dororo2","Learn Less"alert (Au1.getname ()); alert (Au2.getname ()) ;

This method avoids the problem of function implementation, which cannot inherit prototype. Because author.prototype=new person (name), the new person () instance invokes all the properties of the person construct and prototype. But the disadvantage is that Author.prototype has been instantiated. So when the subclass is instantiated, all non-basic data types are reference copy. So the above example, whether the instance AU1, or AU2 returns the value is Dororo1.

Third, with "hybrid" implementation
function Person (name) { This. Name =name;} Person.prototype.getName=function () {return  This. Name; function Author (name, books) { This.Base=NewPerson (name);  for(varKeyinch  This.Base){        if(! This[key]) {            This[key]= This.Base[key]; }           }     This. book=Books;}varau1=NewAuthor ("Dororo1"," Work");varAu2=NewAuthor ("Dororo2","Play"alert (Au1.getname ()); alert (Au2.getname ()); Au1.book;au2.book; 

belongs to the extension, which copies all the fields of the parent class to the subclass. There is no such thing as these two aspects at all.
Parasitic combination mode)

The inheritance of JS includes inheritance of attributes and inheritance of methods, and they are implemented by different methods respectively.
1. Inheritance of attributes

The inheritance of attributes is achieved by changing the execution environment of the function. The execution environment that alters the function can be implemented using both the call () and the Apply () methods.

We first create a animal "class" (because there is no class concept in JS, this is just a simulation, it is actually just a function object).

function Animal (typeName) {//adds an attribute to the execution environment (this) of the current method typename//but the execution environment (this) executes this function in order to determine This. TypeName =TypeName; This. colors = ["Red"," while"];}//to add two (object-shared) methods to the prototype of a functionAnimal.prototype.Shout = function () {alert ("I am:--"+ This. typeName);}; Animal.prototype.Eat= function () {alert ("I am:--"+ This. TypeName)};//-- define a lion--"class" (which is actually a function)function Lion (TN) {//--Executes the animal method and modifies the animal execution environment for Lion's this by using the first parameter of apply//Likewise, the this of lion is to be determined at the time of execution.Animal.apply ( This,["Lions"]);//--Inherits the variable attribute of the parent class, this is because it is new lion,this is Lion}lion.prototype= Animal.prototype;//The way to inherit the parent class--but this is not good, when the subclass adds the method again, the parent class also has this method, which is the pointer referenceLion.prototype.Hunt =function () {alert ("I'm: Lion, I'm going to hunt ~~ ~ .");}varAMINM =NewAnimal (); aminm. Hunt (); //---can access the methods of subclasses, so it's not good.//----So how to solve this problem??????? //---Solution: The inheritance method can be written like this:Lion.prototype =NewAnimal ();//inherits the method of the parent class, assigns the animal object to the prototype prototype, in fact it also has the attributevarLion =NewLion ();//The new keyword, in addition to creating, modifies the execution environment of the Lion object to the Lion object itself//---in other words, when new is done, this is the lion function itself, and then the Lion function is called.
New Keyword Action parsing:

The New keyword is great, and in the previous code, the new keyword has done the following:

    1. Open up heap space to prepare to store lion objects
    2. Modifies the execution environment of the Lion object itself so that this of the lion function points to the Lion function object itself.
    3. Call the "constructor" of the Lion "class" to create a Lion object
    4. Assign the heap address of the Lion function object to the variable L, and this time L points to the Lion function object
      Lion. Shout (); Lion. Eat ();

      But there is a drawback to this inheritance: that is, the constructor of the parent class is called two times, call once, and then new again.

Inheritance usage in JavaScript

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.