zoukankan      html  css  js  c++  java
  • 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();

    }

  • 相关阅读:
    .net操作cookies
    sqlserver 自增列清零
    数据库之mysql视图、触发器、事务、存储过程、函数等相关内容-47
    知识补充之面向对象魔法方法及mysql等相关内容
    数据库之mysql多表查询(子查询)以及pymysql等相关内容-46
    数据库之mysql多表查询(连表)以及pymysql等相关内容-45
    数据库之mysql约束条件、表关系、记录操作等相关内容-44
    数据库之mysq修改表、表字段类型等相关内容-43
    数据库之mysql基础等相关内容-42
    并发编程之基于协程的高并发服务端、面向对象回顾等相关内容-41
  • 原文地址:https://www.cnblogs.com/toward-the-sun/p/4033351.html
Copyright © 2011-2022 走看看