[原]JavaScript必备知识系列-继承的实现方式
JavaScript实现继承的几种方式
开发中常见的几种JavaScript继承方式,了解每一种都会有提高的,直接贴代码吧,更直接。
具体的JavaScript面向对象的概念理解参见JavaScript必备知识系列-面向对象知识串结
JavaScript必备知识系列,总目录参见JavaScript必备知识系列-开篇
拷贝继承
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; }
forEach方法参见JavaScript必备知识系列-Array
原型链继承(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; } };
拷贝+原型链继承(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是View、Model或Collection,protoProps为自定义属性,staticProps默认静态属性 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本身定义为一个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是一个空的构造函数 child.prototype = new ctor();//child原型继承parent的原型 // Add prototype properties (instance properties) to the subclass, // if supplied. if (protoProps) _.extend(child.prototype, protoProps); //拷贝自定义属性给child的原型上 // 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; //此时的child是一个功能强大的方法了,还是一个function };