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};