Javascript模仿接口可以有三种方式:1.注释法 2.检查属性法 3.鸭式辨形法
1.注释法:此方法属于程序文档范畴,对接口的继承实现完全依靠程序员自觉
var woman = function(name){ //implements People interfacethis.name = name;}woman.prototype.showName = function(){alert(this.name);}woman.prototype.createBody = function(){ //实现必要的方法alert("身体已经创建好");}woman.prototype.createHead = function(){alert("头部已经创建好");}
//2.属性检查法:把要实现的接口方法添加到类属性列表里,通过定义好的检测反复检查是否已经实现了那些方法
//优缺点:可以强迫程序员实现接口,没实现就报错。不过虽然声明了自己实现了哪些方法,但实现时很可能有遗漏
var woman = function(name){this.name = name;this.implementsInterfaces = ['People'];}woman.prototype.showName = function(){alert(this.name);}woman.prototype.createBody = function(){ //实现必要的方法alert("身体已经创建好");}woman.prototype.createHead = function(){alert("头部已经创建好");}function implement(obj,interfaces){for(var i=1;i<interfaces.length;i++){var interfaceName = interfaces[i];var interfaceFound = false;for(var j=0;j<obj.implementsInterfaces.length;j++){if(obj.implementsInterfaces[j] = interfaceName){interfaceFound = true;break;}}if(!interfaceFound){return false;}}return true;}function isImplememts(instance,interfaces){ //判断对象是否已经继承相应接口if(!implement(instance,interfaces)){throw new Error("Object doesn't implement a required interface");}}
3.鸭式辨型法:(不通过外表判断鸭子,而通过其是否有鸭子的特性来判断。如James Whitcomb Riley所说,像鸭子一样走路并且嘎嘎叫的就是鸭子)
上面俩种都声明了自己实现了那些接口,其实声明不重要,实现接口核心的是类实现了接口方法集。如果类具有了接口定义的所有方法函数名相同的函数,那么认为它实现了接口
//接口类,用来创建接口var Interface = function(name,motheds){if(agruments.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<motheds.length;i++){if(typeof motheds[i] !== 'string'){throw new Error('Interface constructor expects mothed names to be'+'passes in as a string');}this.methods.push(motheds[i]);}}Interface.prototype.ensureImplements = function(objs){if(agruments.length != 1){throw new Error("Interface constructor called with "+arguments.length+"arguments,but expected exactly 1")}for(var i=0;i<objs.length;i++){var obj = objs[i];for(var j=0;j<this.motheds.length;j++){var mothed = this.methods[j];if(!obj[mothed] || !typeof obj[mothed] !== 'function'){throw new Error('Function Interface.ensureImplements:implements interface'+this.name+',obj.mothed'+mothed+'was not found');}}}}//创建接口var People = new Interface('People',['createHead','createBody']);//子类var Woman = function(name){this.name = name;this.implementsInterfaces = ['People'];}Woman.prototype.showName = function(){alert(this.name);}Woman.prototype.createBody = function(){ //实现必要的方法alert("女人身体已经创建好");}Woman.prototype.createHead = function(){alert("女人头部已经创建好");}//子类var Man = function(name){this.name = name;this.implementsInterfaces = ['People'];}Man.prototype.showName = function(){alert(this.name);}Man.prototype.createBody = function(){ //实现必要的方法alert("男人身体已经创建好");}Man.prototype.createHead = function(){alert("男人头部已经创建好");}//判断是否实现Poeple.ensureImplements(['Woman','Man']);