js接口練習


 1     /**
 2      * 創建接口對象
 3      * @param name 接口名 
 4      * @param methods 接口方法
 5      */
 6     var Interface = function(name,methods){
 7         if(arguments.length != 2){
 8             throw new Error('必須輸入兩個參數,當前個數'+arguments.length);
 9         }
10 
11         this.name=name;
12         this.methods=[];
13         for(var i=0, len=methods.length; i<len; i++){
14             if(typeof methods[i] !== 'string'){
15                 throw new Error('方法名參數必須為string');
16             }
17             this.methods.push(methods[i]);
18         }
19     };
20     /**
21      * 接口實現
22      * @param  object1 實現接口對象
23      * @param  object2 對應接口
24      * @return 實現錯誤拋出異常
25      */
26     Interface.ensureImplements = function(object){
27         if(arguments.length < 2){
28             throw new Error('必須輸入兩個參數,當前個數' + arguments.length);
29         }
30         for(var i=1, len=arguments.length; i < len; i++){
31             var interface = arguments[i];
32             if(interface.constructor != Interface){
33                 throw new Error("請實現接口");
34             }
35 
36             for (var j = 0, methodsLen = interface.methods.length; j < methodsLen; j++){
37                 var method = interface.methods[j];
38                 if(!object[method] || typeof object[method] !== 'function'){
39                     throw new Error("接口名:"+interface.name+"方法名:"+method+"沒找到");
40                 }
41             };
42         }
43     }
44 
45 
46     var DynamicMap = new Interface('DynamicMap',['centerOnPoint','zoom','draw']);
47 
48     /**
49      * 執行方法
50      * @param  函數方法
51      * @return 執行結果
52      */
53     function displayRoute(mapInstance){
54         Interface.ensureImplements(mapInstance,DynamicMap);//實現接口
55 
56         /**
57          * 調用
58          */
59         mapInstance.centerOnPoint(12,34);
60         mapInstance.zoom(5);
61         mapInstance.draw();
62     }
63     /**
64      * 函數方法
65      * @type 實現接口方法
66      */
67     var a={
68         centerOnPoint:function(x,y){
69             console.log(x*y);
70         },
71         zoom:function(x){
72             console.log(x);
73         },
74         draw:function(){
75             console.log("x*y");
76         }
77     }
78     displayRoute(a);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM