继承的话我这里主要是传统的原型继承方式。关于原型继承,这个在网上已经有现有的轮子了(参考了慕课网Bosn老师的JavaScript深刻浅出一篇的原型继承的视频讲解),我就站在巨人的肩上给稍微改动了下了app
Object.prototype.extends = function(SuperClass) { if(!Object.create) { Object.create = function(proto) { function F() { F.prototype = proto; return new F; } } } var oldPrototype = this.prototype; this.prototype = Object.create(SuperClass.prototype); // this.prototype.constructor = SuperClass; for(key in oldPrototype) { oldPrototype[key] !=undefined && (this.prototype[key]=oldPrototype[key]); } this.prototype.__parent__ = SuperClass; }; Object.prototype.super = function() { var param = arguments[0]; var arg = arguments; while(param) { if(!param.callee) { break; } arg = param; param = param[0]; } var parent = this; while(parent) { for(var key in parent) {//首次子类调用该方法 if(arguments[0].callee == parent[key]) {//找到对应父类 arg.callee = arguments[0].callee; parent.__parent__.prototype[key].apply(this, arg); return; } } for(var key in parent.prototype) { if(arguments[0].callee == parent.prototype[key]) {//找到对应父类 arg.callee = arguments[0].callee; parent.prototype.__parent__.prototype[key].apply(this, arg); return; } } parent = parent.__parent__; } }; Object.defineProperties(Object.prototype, { 'extends': { enumerable: false, writable: false }, 'super': { enumerable: false, writable: false } });
使用例子:this
var Person = function() {}; Person.prototype = { say: function() { console.log("person say"); } }; var Father = function() {}; Father.prototype = { say: function() { this.super(arguments); console.log("father say"); } } Father.extends(Person); var Son = function() {}; Son.prototype = { say: function() { this.super(arguments); console.log("son say"); } } Son.extends(Father); var son = new Son(); son.say(); var Daughter = function() {}; Daughter.prototype = { say: function() { this.super(arguments); console.log("daughter say"); } } Daughter.extends(Father); var daughter= new Daughter(); daughter.say();
/************* 打印结果 ***************/.net
person say father say son say person say father say daughter say
多态主要是在方法里面经过调用this.super(arguments)就会自动向上调用父类的同名方法。以上即是本次的js代码库分享,但愿你们多多指点、多多评论,也但愿我之后能给你们带来更多有用的库方法或者类。欢迎转载,原文出处 http://www.javashuo.com/article/p-adskjsfx-dw.htmlprototype