Several methods of JavaScript implementation inheritance
There are several common JavaScript inheritance methods in development. To learn more about each of them, paste the Code directly.
For a specific understanding of JavaScript object-oriented concepts, see the essential knowledge series of JavaScript-Object-Oriented Knowledge string
A series of essential knowledge of JavaScript. For more information, see the series of essential knowledge of JavaScript.
Copy inheritance
extend(obj) {var args = Array.prototype.slice.call(arguments, 1);args.forEach(function(source) {for(var prop in source) {obj[prop] = source[prop];}});return obj;}
For the forEach method, see the essential knowledge series of JavaScript-Array
Prototype chain inheritance (YUI)
YAHOO.extend = function(subclass, superclass) { var f = function() {}; f.prototype = superclass.prototype; subclass.prototype = new f(); subclass.prototype.constructor = subclass; subclass.superclass = superclass.prototype; if (superclass.prototype.constructor == Object.prototype.constructor) { superclass.prototype.constructor = superclass; } };
Copy + prototype chain inheritance (Backbone)
// Shared empty constructor function to aid in prototype-chain creation. var ctor = function () {}; // Helper function to correctly set up the prototype chain, for subclasses. // Similar to 'goog. inherits ', but uses a hash of prototype properties and // class properties to be extended. // parent is View, Model, or Collection, protoProps is a custom attribute, staticProps default static attribute var inherits = function (parent, protoProps, staticProps) {var child; // The constructor function for the new subclass is either defined by you // (the "constructor" property in your 'extend' definition ), or defaulted // by us to simply call the parent's constructor. if (protoProps & protoProps. hasOwnProperty ('constructor') {child = protoProps. constructor;} else {child = function () {parent. apply (this, arguments) ;}; // child itself is defined as a function} // Inherit class (static) properties from parent. _. extend (child, parent); // Set the prototype chain to inherit from 'parent', without calling // 'parent' s constructor function. ctor. prototype = parent. prototype; // ctor is an empty constructor child. prototype = new ctor (); // the child prototype inherits the parent prototype // Add prototype properties (instance properties) to the subclass, // if supplied. if (protoProps )_. extend (child. prototype, protoProps); // copy the custom attributes to the child prototype. // Add static properties to the constructor function, if supplied. if (staticProps )_. extend (child, staticProps); // Correctly set child's 'prototype. constructor '. child. prototype. constructor = child; // Set a convenience property in case the parent's prototype is needed later. child. _ super _ = parent. prototype; return child; // at this time, the child is a powerful method, or a function };