[原]JavaScript必備知識系列-繼承的實現方式

來源:互聯網
上載者:User
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};

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.