js中接口的声明与实现

实现接口,必须实现接口里的所有方法。

function Interface(name,fns){//声明一个接口类
            this.name = name;
            this.methods=[];
            for(var i=0;i<fns.length;i++){
                if(typeof fns[i] != 'string')
                    throw new Error("方法名必须是字符串,必须传字符串数组");
                this.methods.push(fns[i]);
            }
        }
        var face1 = new Interface('face1',['add','edit']);//创建接口对象,该接口声明了两个需要实现的方法add和edit
        var face2 = new Interface('face2',['del','save']);
        Interface.ensureImplements = function(obj){//定义检测是否实现接口的函数,可以传一个或多个接口对象
            if(arguments.length<2){
                throw new Error("至少要传两个参数");
            }
            for(var i=1;i<arguments.length;i++){
                if(arguments[i].constructor != Interface){
                throw new Error("这个不是接口对象,请传接口对象");
                }

                for(var j=0;j<arguments[i].methods.length;j++){
                
                if(!(obj[arguments[i].methods[j]]) || typeof obj[arguments[i].methods[j]] != 'function'){
                    throw new Error("没实现接口里的所有方法");
                }
            }

            }      
        }

    function dd(){//声明一个类实现接口的所有方法
            this.name="yes";
            this.add=function(){

            }
            this.del=function(){}
            this.edit=function(){}
            this.save=function(){}
        }

var kk = new dd();

Interface.ensureImplements(kk,face1,face2);//检测kk对象是否实现了face1和face2两个接口

通常,如果一个类的参数是另一个类的对象时,我们会用到接口技术。

function Demo(kk){

  Interface.ensureImplements(kk,face1,face2);

  this.formaction = kk;//将dd类的对象传给Demo类的formaction属性。

}

Demo.prototype.operation = function(){

  var sdata = this.formaction.save();

}

原文地址:https://www.cnblogs.com/toward-the-sun/p/4033351.html