[原]JavaScript必备知识系列-继承的实现方式
2012-09-13 21:29
645 查看
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 };
相关文章推荐
- 讲述Javascript 实现继承的方式(基础知识)
- JavaScript实现继承的六种方式
- javascript中实现对象继承的五种方式详解
- javascript中实现继承的最佳方式
- JavaScript面向对象-基于函数伪造的方式实现继承
- 详述JavaScript实现继承的几种方式(推荐)
- JavaScript中实现继承的三种方式和实例
- 【JavaScript】实现继承的方式
- javascript实现继承的几种方式
- JavaScript中实现继承的几种方式的使用和分析
- [原]JavaScript必备知识系列-Array
- JavaScript实现继承的方式优化
- JavaScript实现继承的几种方式
- javascript中实现继承的三种方式(一看就懂)
- Javascript 实现继承的三种方式
- (转)js(javascript) 继承的5种实现方式
- JavaScript学习系列之深入原型链与继承的实现
- JavaScript 中实现继承的方式(列举3种在前一章,我们曾经讲解过创建类的最好方式是用构造函数定义属性,用原型定义方法。)
- JavaScript 中继承实现方式归纳