js20---接口3种方式

简介:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Untitled Document</title>
        <script type=text/javascript charset=utf-8>
        //javascript没有定义接口的概念,我们通过模拟高级程序语言的方式来创建javascript中的接口。实现要重写接口所有的方法。
        /* javascript定义接口有三种方式
        1 注释描述接口
        2 属性检测接口
        3 鸭式辩型接口
        */
        
        // 1 注解描述的方式(注释方式,假的)
        /**
        interface Composite {
            function add(obj);
              function remove(obj);
             function uopdate(obj);
        }
        
        var CompositeImpl = function(){
            this.add = function(){},
            this.remove = function(){},
            this.upload = function(){}
        };
        var c1 = new CompositeImpl();
        var c2 = new CompositeImpl();
        alert(c1.add == c2.add); //false,每次都有一个add,所以写到原型里面
        */
        
        // CompositeImpl implements Composite
        var CompositeImpl = function(){
        };
        
        CompositeImpl.prototype.add = function(obj){
        }
        CompositeImpl.prototype.remove = function(obj){
        }            
        CompositeImpl.prototype.update = function(obj){
        }
                    
        var c1 = new CompositeImpl();
        var c2 = new CompositeImpl();
        alert(c1.add == c2.add);
        </script>
    </head>
    <body>
    </body>
</html>
复制代码
复制代码
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Untitled Document</title>
        <script type=text/javascript charset=utf-8>
        // 第二种实现接口的方式 属性检测的方式(继承接口,就要实现所有方法。)
        /**
         *     interface Composite {
         *         function add(obj);
         *         function remove(obj);
         *        function uopdate(obj);
         *  }
         *  
         *  interface FormItem {
         *      function select(obj);
         *  }
         *  
         */        
         
         // CompositeImpl implements Composite , FormItem
         var CompositeImpl = function(){
            // 显示的再类的内部 接受所实现的接口
            // 一般来说是一个规范 我们项目经理:在类的内部定义一个数组(名字要固定)
            this.implementsInterfaces = ['Composite' ,'FormItem' ];//this是这个类的当前对象
         }    
         
         
        CompositeImpl.prototype.add = function(obj){
            alert('add...');
        }
        CompositeImpl.prototype.remove = function(obj){
        }            
        CompositeImpl.prototype.update = function(obj){
        }            
        CompositeImpl.prototype.select = function(obj){
        }        
        
        
        // 检测CompositeImpl类的对象的
        function CheckCompositeImpl(instance){
            //判断当前对象是否实现了所有的接口
            if(!IsImplements(instance,'Composite','FormItem')){
                throw new Error('Object does not implement a required interface!');
            }
        }
        
        function IsImplements(object){//实参多个,形参一个,这个形参就是实参的第一个,
            // arguments 对象 获得函数的实际参数
            for(var i = 1 ; i < arguments.length;i++){
                //接受所实现的每一个接口的名字
                var interfaceName = arguments[i];//arguments[i]在不在object.implementsInterfaces里面
                var interfaceFound = false ;
                for(var j = 0 ; j <object.implementsInterfaces.length;j++){
                        if(object.implementsInterfaces[j] == interfaceName)    {
                            interfaceFound = true ;
                            break;//跳出for循环
                        }
                }
                if(!interfaceFound){
                    return false ; 
                }
            }
            return true ; 
        }
        
        var c1 = new CompositeImpl();
        CheckCompositeImpl(c1);
        c1.add();
        </script>
    </head>
    <body>
    </body>
</html>
复制代码
复制代码
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Untitled Document</title>
        <script type=text/javascript charset=utf-8>
        // 实现接口的第三种方式:鸭式辨型法实现接口(最完美的javascript实现接口方式)
        // 鸭式辨型法实现的核心:一个类实现接口的主要目的:把接口里的方法都实现(检测方法)
        // 完全面向对象 代码也实现统一  也解耦了
        
        // 一: 接口类 Class Interface ==>实例化N多个接口
        
        /**
         * 接口类需要2个参数
         * 参数1: 接口的名字 (string)
         * 参数2: 接受方法名称的集合(数组) (array)
         */
        var Interface = function(name,methods){
            //判断接口的参数个数
            if(arguments.length != 2){
                throw new Error('this instance interface constructor arguments must be 2 length!');
            }
            this.name = name ; 
            this.methods = [] ; //定义一个内置的空数组对象 等待接受methods里的元素(方法名字)
            for(var i = 0,len = methods.length ; i <len ; i++){
                 if( typeof methods[i] !== 'string'){
                        throw new Error('the Interface method name is error!');
                 }
                 this.methods.push(methods[i]);
            }
        }
        
        // 1 实例化接口对象
        var CompositeInterface = new Interface('CompositeInterface' , ['add' , 'remove']);//CompositeInterface对象有属性name为CompositeInterface,数组['add' , 'remove']
        var FormItemInterface  = new Interface('FormItemInterface' , ['update','select']);
        //  CompositeImpl implements CompositeInterface , FormItemInterface
        var CompositeImpl = function(){
        } 
        // 3 实现接口的方法implements methods             
        CompositeImpl.prototype.add = function(obj){
            alert('add');
        }
        CompositeImpl.prototype.remove = function(obj){
            alert('remove');
        }            
        CompositeImpl.prototype.update = function(obj){
            alert('update');
        }    
        /*            
        CompositeImpl.prototype.select = function(obj){
            alert('select');
        }    
        */
        
        // 三:检验接口里的方法
        Interface.ensureImplements = function(object){
            // 如果检测方法接受的参数小于2个 参数传递失败!
            if(arguments.length < 2 ){
                throw new Error('Interface.ensureImplements method constructor arguments must be  >= 2!');
            }
            
            for(var i = 1 , len = arguments.length; i<len; i++ ){
                var instanceInterface = arguments[i];
                // 判断对象是不是一个类的实例,判断对象的构造器是不是类名字
                if(instanceInterface.constructor !== Interface){
                    throw new Error('the arguments constructor not be Interface Class');
                }
                // 循环接口实例对象里面的每一个方法
                for(var j = 0 ; j < instanceInterface.methods.length; j++){
                    // 用一个临时变量 接受每一个方法的名字(注意是字符串)
                    var methodName = instanceInterface.methods[j];
                    if( !object[methodName] || typeof object[methodName] !== 'function' ){
                        throw new Error("the method name '" + methodName + "' is not found !");
                    }
                }
            }
        }
        
        var c1 = new CompositeImpl();
        Interface.ensureImplements(c1,CompositeInterface,FormItemInterface);
        c1.add();
        </script>
    </head>
    <body>
    </body>
</html>
复制代码
复制代码
var CompositeImpl = function(){} 
CompositeImpl.prototype.add = function(obj){
    alert('add');
}

var c1 = new CompositeImpl();
alert(c1['add']);//function(obj){alert('add');}
alert(c1['ssadd']);//undefined
alert(c1['sss']);//undefined,
alert(c1.ssadd());//ssadd is not a function
alert(c1.sss);//undefined,  没有属性,方法,通过中括号返回未定义,就是假
c1['add'];//什么都没有
alert(typeof c1['add']);//function



if( !c1[methodName] || typeof c1[methodName] !== 'function' ){
    throw new Error("the method name '" + methodName + "' is not found !");
}// c1[methodName]有可能是一个属性,不是方法。  !==

// 判断对象是不是一个类的实例,判断对象的构造器是不是类名字
instanceInterface.constructor !== Interface
复制代码

 


本文转自农夫山泉别墅博客园博客,原文链接:http://www.cnblogs.com/yaowen/p/6879384.html,如需转载请自行联系原作者

相关文章
|
3月前
|
JavaScript 前端开发
JS实现继承的6种方式
JS实现继承的6种方式
|
7天前
|
JavaScript 前端开发
Js实现继承的6种方式
Js实现继承的6种方式
|
3月前
|
JavaScript 前端开发
js定义函数的三种方式
js定义函数的三种方式
10 0
|
8月前
|
JavaScript 前端开发 C#
js代码如何封装
js代码如何封装
69 0
|
JavaScript
JS的调用方式
JS的调用方式
|
前端开发 JavaScript
前端 js 继承的n种方式
前端 js 继承的n种方式
86 0
|
JavaScript
js是如何实现new一个对象的?
面向对象,从new一个对象开始。在ES6中,引入了关键词`class`来声明一个类,在此之前想要创建一个"类",只能使用函数的方式。可以说,`class`其实就是函数`function`的一个语法糖。有了类,我们就可以使用`new`来创建一个实例对象。
462 0
js是如何实现new一个对象的?
第201天:js---实现继承的5种方式
一、构造函数方式 1 //构造函数 2 function People(){ 3 this.race = '汉族'; 4 } 5 People.prototype={ 6 eat:function(){ 7 console.
1039 0
|
索引 vr&ar
第199天:js---扩充内置对象功能总结
一、数组 1、删除数组中指定索引的数据 1 /** 删除数组中指定索引的数据 **/ 2 Array.prototype.deleteAt = function (index) { 3 if (index < 0) { 4 return this; 5 } 6 return this.
842 0