JS实现继承多态
//类对象构造模版,无new访问,类似静态访问 var Class = { create: function () { return function () { //initialize初始化 //apply应用变更,可以反复请求 //arguments参数 this.initialize.apply(this, arguments) }; }, //模拟抽象方法,可以随便自己定 Show: function () { } }; //模拟继承extobj扩展对象,srcobj源对象 var Extend = function (extobj, srcobj) { for (var a in srcobj) { extobj[a] = srcobj[a]; } return extobj; }; //动态为Object添加extend方法,用来完成继承 Object.prototype.extend = function (obj) { return Extend.apply(this, [this, obj]); }; //实例演示 var ClassAB = Class.create(); ClassAB.prototype = { //初始函数,相当于构造方法 initialize: function (name) { this.name = name; }, Show: function (a) { this.abstractShow(a); //抽象方法 } }; //继承 var ClassA = Class.create(); ClassA.prototype = new ClassAB(null).extend({ Show: function (a) { //实现抽象方法 alert(this.name + " " + typeof (this) + " " + a); } }); var ClassB = Class.create(); ClassB.prototype = new ClassAB(null).extend({ Show: function (a) { //实现抽象方法 alert(this.toString + " " + typeof (this) + " " + a+new Date().toDateString()); } }); //多态 ClassAB = new ClassA("ClassA"); ClassAB.Show("hello"); ClassAB = new ClassB("ClassB"); ClassAB.Show("hello");