JavaScript Inheritance at a glance

Source: Internet
Author: User
Tags shallow copy

Inheritance is an essential part of every JavaScript tool library and framework. Let's take a look at the implementation of each big class library.

1, Prototype.1.7.1.js

function extend (destination, source) {    for(var in source)       = source[ Property];     return destination;  }

2, the famous jquery.2.0.3

Jquery.extend = JQuery.fn.extend =function() {    varoptions, name, SRC, copy, Copyisarray, clone, Target= Arguments[0] | |{}, I= 1, Length=Arguments.length, deep=false; //Handle a deep copy situation    if(typeoftarget = = = "Boolean") { deep=Target; Target= Arguments[1] | | {}; //Skip the Boolean and the targeti = 2; }    //Handle Case If Target is a string or something (possible in deep copy)    if(typeofTarget!== "Object" &&!jquery.isfunction (target)) {Target= {}; }    //extend JQuery itself if only one argument is passed    if(length = = =i) {target= This; --i; }     for(; i < length; i++ ) {        //Only deal with non-null/undefined values        if(options = arguments[i])! =NULL ) {            //Extend the Base object             for(Nameinchoptions) {src=target[name]; Copy=options[name]; //Prevent Never-Ending Loop                if(target = = =copy) {                    Continue; }                //Recurse If we ' re merging plain objects or arrays                if(Deep && copy && jquery.isplainobject (copy) | | (Copyisarray =jquery.isarray (copy))) ) {                    if(Copyisarray) {Copyisarray=false; Clone= src && jquery.isarray (src)?src: []; } Else{Clone= src && jquery.isplainobject (src)?src: {}; }                    //never move original objects, clone themtarget[name] =jquery.extend (deep, clone, copy); //Don ' t bring in undefined values}Else if(Copy!==undefined) {target[name]=copy; }            }        }    }    //Return the Modified object    returntarget;};

The code is so much more, a lot more deep copy and function way

3, underscore

function (obj) {    function(source      ){if  (source) {        for ( var inch source) {          = Source[prop];}}    );     return obj;  };

4, huge angular.

function Extend (DST) {  var h = dst.$ $hashKey;   function (obj) {    if (obj!== dst) {      function(value, key) {        = ( value;      });}  );  Sethashkey (dst,h);   return DST;}

5, Ligerui used in the first project

Function.prototype.ligerExtend =function(parent, overrides) {if(typeofParent! = ' function ')return  This; //Save a reference to the parent class     This. Base =Parent.prototype;  This. Base.constructor =parent; //Inheritance    varf =function () { }; F.prototype=Parent.prototype;  This. prototype =Newf ();  This. Prototype.constructor = This; //Additional Property Methods    if(Overrides) $.extend ( This. prototype, overrides);};

6, Dojo

Extendfunction(ctor, props) {//Summary:            //Adds All properties and methods of props to constructor ' s            //prototype, making them available to all instances created with            //constructor.            //Ctor:object            //Target constructor to extend.            //Props:object            //One or more objects to mix into Ctor.prototype             for(varI=1, L=arguments.length; i<l; i++) {lang._mixin (Ctor.prototype, arguments[i]); }            returnctor//Object},
_mixin:function(dest, source, Copyfunc) {//Summary:            //Copies/adds All properties of the source to dest; returns DEST.            //Dest:object            //The object to which to copy/add any properties contained in source.            //Source:object            //The object from which to draw all properties to copy into Dest.            //copyfunc:function?            //The process used to copy/add a property in source, defaults to the Javascript assignment operator.            //returns:            //dest, as modified            //Description:            //All properties, including functions (sometimes termed "methods"), excluding any non-standard extensions            //found in Object.prototype, is copied/added to Dest. Copying/adding particular property is            //Delegated to Copyfunc (if any), Copyfunc defaults to the Javascript assignment operator if not provided.            //Notice that by default, _mixin executes a so-called "shallow copy" and aggregate types is copied/added by ref Erence.            varName, S, I, empty = {};  for(Nameinchsource) {                //The (!) ( Name in empty) | | Empty[name]!== s) condition avoids copying properties in "source"                //inherited from Object.prototype. For example, if dest have a custom toString () method,                //don ' t overwrite it with the ToString () method, the source inherited from Object.prototypes =Source[name]; if(! (NameinchDest) | | (Dest[name]!== s && (! ( NameinchEmpty) | | Empty[name]!==s))) {Dest[name]= Copyfunc?Copyfunc (s): s; }            }            if(Has ("bug-for-in-skips-shadowed")){                if(source) { for(i = 0; i < _extralen; + +)i) {Name=_extranames[i]; S=Source[name]; if(! (NameinchDest) | | (Dest[name]!== s && (! ( NameinchEmpty) | | Empty[name]!==s))) {Dest[name]= Copyfunc?Copyfunc (s): s; }                    }                }            }            returnDest//Object},

In addition to 5, the basic use of copy-type inheritance. Simple, universal (array, object inheritance is also very useful, like)

6 is the prototype inheritance

Of course, there are other ways, but it doesn't really work much.

Like what:

Object impersonating inheritance

functionParent (firstname) { This. fname=FirstName;  This. age=40;  This. sayage=function() {Console.log ( This. Age); }  }  functionChild (FirstName) { This. parent=Parent;  This. Parent (FirstName); Delete  This. Parent;  This. saysomething=function() {Console.log ( This. fname);  This. Sayage (); }  }  varMychild=NewChild ("Lee"); Mychild.saysomething (); 

Using the call method to change the function context implementation inheritance

functionParent (firstname) { This. fname=FirstName;  This. age=40;  This. sayage=function() {Console.log ( This. Age); }  }  functionChild (FirstName) { This. saysomething=function() {Console.log ( This. fname);  This. Sayage (); }      This. getname=function()     {         returnFirstName; }    }  varChild=NewChild ("Zhang");  Parent.call (Child,child.getname ()); Child.saysomething (); 

The above is to find out how to inherit the large class library and some inherited methods on the network.

Recommendation: Copy-type inheritance, although performance is almost.

JavaScript inheritance at a glance

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.