首页 > web前端 > js教程 > 正文

JavaScript设计模式之一Interface接口

高洛峰
发布: 2016-11-25 11:09:22
原创
1883人浏览过

如何用面向对象的思想来写javascript,对于初学者应该是比较难的,我们经常用的jquery其实也是用面向对象的思想去封装的,今天我们来看看如何在javascript中用interface,在c#还是java中都应该面向接口设计我们的程序,在c#和java中都interface这样的关键字,但是javascript中没有相应的机制,但是javascript很灵活,我们可以用它的特性去模仿interface,但是我们需要加入一些methods来做check的动作。
我们来看下一个interface的作用: 

继承了这个Interface就必须要实现这个Interface中定义的方法(方法签名)

//JavaScript 现在还做不到方法的签名的约束
var Interface = function (name, methods) {     

   if (arguments.length != 2) {     

      throw new Error("the interface length is bigger than 2");      

立即学习Java免费学习笔记(深入)”;

  }      

  this.Name = name;     

   this.Method = [];     

   for (var i = 0; i

      if(typeof methods[i]!== string) {    

    throw new Error("the method name is not string");    

    }        this.Method.push(methods[i]);   

     }   

 }  

  /*static method in interface*/  

  Interface.ensureImplement = function (object) {  

      if (arguments.length

           throw new Error("there is not Interface or the instance"); 

       }       

 for (var i = 1; i

          var interface1 = arguments[i];      

      if (interface1.constructor !== Interface) {               

 throw new Error("the argument is not interface");           

 }            

for (var j = 0; j

 var method = interface1.Method[j];               

 if (!object[method] || typeof object[method] !== function) {                  

  throw new Error("you instance doesnt implement the interface");                                 

  }          

  }     

   }   

 }
我们来分析一下code,我们现在的做法是用来比较一个Instance中的方法名在接口中是否定义了。
我先定义一个接口(2个参数),第二个参数是接口中的方法名。Check方法用简单的2层for循环来做比较动作。
我们来看下如何去用这个接口:
 var Person = new Interface("Person", ["GetName", "GetAge"]);      var Man = function (name, age) {        this.Name = name;        this.Age = age;    }    Man.prototype = { GetName: function () { return this.Name; },      //  GetAge: function () { return this.Age; }    }    var test = function (instance) {               Interface.ensureImplement(instance, Person);           var name = instance.GetName();        alert(name);    }    test(new Man("Alan",20));
如果我们注释了上面的GetAge方法,在执行的时候就会出错。在ensureImplement的时候发现并没有去实现这个方法。

java速学教程(入门到精通)
java速学教程(入门到精通)

java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号