JavaScript code reuse mode (iii)

Source: Internet
Author: User

The class inheritance of JavaScript is discussed earlier. This continuation of the classification of inheritance, and some modern inheritance.

Class inheritance mode-proxy constructors

This pattern solves the problem of sharing a prototype from the last mentioned by disconnecting the direct link between the parent and child objects, and can continue the benefits of the prototype chain.

Code:

function inherit (c,p) {    varfunction() {};     = P.prototype;     New F ();}

As you can see, in this there is an empty constructor F (), which acts as a proxy between the child object and the parent object, and the prototype of F () points to the prototype of the parent object. The prototype of a child object is a blank function instance.
This pattern is somewhat different from the default stereotype inheritance pattern because the child objects here inherit only the properties of the prototype. This is ideal and preferable, because the prototype is where the multiplexing function is placed. In this mode, the parent constructor that is added to this member is not inherited. As follows:

You can create a child object:

var New Child ();

When accessing Kid.say (), there is no method found in object 3 and the prototype chain needs to be queried. Object 4 also does not have, Object 1 has, can call this method.
In a real-world application, you can add a reference to the parent constructor prototype object for use:

function inherit (c,p) {    varfunction() {};     = P.prototype;     New F ();     = P.prototype;}

The following also requires resetting the constructor pointer to use:

 function   Parent () {}  function   child () {}inherit (child,parent);  var  kid = new   child (); kid.constructor.name;  //  kid.constructor = = = parent; // true  
function inherit (c,p) {    function() {};    F.prototype =new F (); C.uber = P.prototype; C.prototype.constructor = C;}      

One of the optimizations that can be done here is to avoid creating an agent constructor every time an inheritance is required, creating only one proxy function, and modifying its prototype, which can already be achieved. On a specific implementation, you can use the call function immediately and store the agent function in the closure:

var inherit =  (fucntion () {    varfunction() {};     return function (c,p) {        = p.prototype;         New F ();         = P.prototype;         = C;    };}) ();    

Modern inheritance-prototype inheritance of objects

This is a class-free inheritance pattern that does not involve classes, where objects are inherited from other objects. Consider this way: there is an object that you want to reuse, and the second object you create is to get the content from the first object.

Code:

var parent = {    name:"Papa"}; var child = object (parent); child.name; // "Papa"

A parent object, created as an object literal, needs to create a child object that has the same properties and methods as the parent, where the object () function is implemented as follows, similar to a class-inherited proxy constructor:

function Object (o) {    function  F () {}    = o;     return New F ();}

Shows the prototype chain using this pattern. Child is initially an empty object, has no properties of its own, and has full functionality of the parent object through the _proto_ link.

In this pattern, you do not need to use object literals to create a parent object, you can actually create it using a constructor, and if you use a constructor, the properties of your own and the prototype properties of the constructor are inherited:

function Person () {    this. Name = "Adam";       own Property function () {return this. name;}; var New Person (); var kid = object (papa); Kid.getname (); // "Adam"

You can actually choose to inherit only the prototype object of an existing constructor, as follows:

function Person () {    this. Name = "Adam";       own Property function () {return this. name;}; var kid = object (person.prototype); typeof Kid.getname (); // function typeof Kid.name; // undefined

In ES5, the prototype inheritance pattern has become part of the language and is implemented through Object.create ():

var child = object.create (parent);

Object.create () accepts another parameter that can pass in an object that will be the property of the new object:

var child = object.create (parent,{    age:{value:2})};child.hasownproperty ("age");   True

Modern inheritance-Inheritance by copying properties

Here is an example of extend ():

function Extend (parent,child) {    var  i;     = child| | {};      for inch parent) {        if(Parent.hasownproperty (i)) {            = parent[i];        }    }     return Child ;}

Here's how to use it:

var dad = {name: "Adam"}; var kid = Extend (dad); kid.name; // "Adam"

The above implementation is shallow copy, deep copy needs to check the property, if the copy is an object or an array, when using shallow copy, if you change the properties of the child object, and the property is an object, the parent object will also be modified, this situation may cause unexpected:

var dad = {    counts:[),    reads:{paper:true}; var kid = Extend (dad); Kid.counts.push (4);d ad.counts.toString (); // "1,2,3,4"dad.reads = = = Kid.reads; // true

For deep replication, you need to modify extend () to determine whether each property is an object or an array:

functionExtenddeep (parent,child) {varI, Tostr=Object.prototype.toString, Astr= "[Object Array]"; Child= child| |{};  for(Iinchparent) {        if(Parent.hasownproperty (i)) {if(typeofParent[i] = = = "Object") {Child[i]= (Tostr.call (parent[i]) = = = Astr?) [] : {};            Extenddeep (Parent[i],child[i]); }Else{Child[i]=Parent[i]; }        }    }    returnChild ;}

Test:

 var  dad = {counts:[ 1,2,3], Reads:{paper:  true   var  kid = Extenddeep (dad); Kid.counts.push (  4 //  dad.counts.toString (); //  dad.reads  = = = Kid.reads; // false  kid.reads.paper = ;d Ad.reads.paper;  // true  

This pattern is widely used, for example Firebug has a extend () method for shallow replication, and extend () in jquery can achieve deep replication.

JavaScript code reuse mode (iii)

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.