类式继承:
function dw(x) {document.writeln(x + "<br />"); }function extend(subClass, superClass) {var F = function(){};F.prototype = superClass.prototype;subClass.prototype = new F();subClass.prototype.constructor = subClass;//superClass属性用来弱化sub,super之间的耦合,可以使用此属性调用超类中的方法subClass.superClass = superClass.prototype;if (superClass.prototype.constructor == Object.prototype.constructor) {superClass.prototype.constructor = superClass;}}function Person(name) {this.name = name; } Person.prototype.getName = function(){return this.name; }function Author(name, books) {Author.superClass.constructor.call(this, name);//Person.call(this, name); //这种方式也可,但将超类名称固化在声明中,增加了耦合this.books = books; } extend(Author, Person); Author.prototype.getBooks = function(){return this.books; } Author.prototype.getName = function(){var name = Author.superClass.getName.call(this);return name + ", Author of " + this.getBooks(); }var a = new Author("tom", "DP"); dw(a.getBooks()); dw(a.getName());
//原型式继承 function clone(object){function F(){};F.prototype = object;return new F; } //混元类 function augment(receivingClass, givingClass){if(arguments[2]){for(var i=2; i<arguments.length; i++){receivingClass.prototype[arguments[i]] = givingClass.prototype[arguments[i]];}}else{for(methodName in givingClass.prototype){if(!receivingClass.prototype[methodName]){receivingClass.prototype[methodName] = givingClass.prototype[methodName];}}} }
接口:
var Interface = function(name, methods){if(arguments.length != 2){throw new Error("Interface constructor called with "+ arguments.length + "arguments,but expected exactly 2.");}this.name = name;this.methods = [];for(var i=0; i<methods.length; i++){if(typeof methods[i] !== "string"){throw new Error("interface need the method name as a string.");}this.methods.push(methods[i]);} } Interface.ensureImplements = function(object){if(arguments.length < 2){throw new Error("Function Interface.ensureImplements called with"+ arguments.length + " arguments,but expected at least 2.")}for(var i=1; i<arguments.length; i++){var interfaceElem = arguments[i];if(interfaceElem.constructor !== Interface){throw new Error("");}for(var j=0; j<interfaceElem.methods.length; j++){var method = interfaceElem.methods[j];if(!object[method] || typeof object[method] !== 'function'){throw new Error(method + " was not found")}}} } //test code var Com = new Interface("Com",['add','remove','save']); var createT = function(){//this.add = function(){};this.remove = function(){};//this.save = function(){}; } var t1 = new createT(); Interface.ensureImplements(t1,Com);
继承: