javascript接口实现之鸭式辨型法
来源:互联网 发布:黑客网站软件免费下载 编辑:程序博客网 时间:2024/05/13 03:08
//接口类var Interface = function(name,methods){if(arguments.length != 2){throw new Error('the interface constructor arguments must be 2 length!');}this.name = name ; //确保methods里的元素为string类型this.methods = [] ;for(var i = 0,len = methods.length ; i <len ; i++){ if( typeof methods[i] !== 'string'){ throw new Error('the interface\'methods name must be a string type!'); } this.methods.push(methods[i]);}}// 检测对象是否实现相应接口中定义的方法// 如果检验通过 不做任何操作 不通过:浏览器抛出errorInterface.ensureImplements = function(object,implInterfaces){// 如果检测方法接受的参数小于2个 参数传递失败!if(arguments.length != 2 ){throw new Error('Interface.ensureImplements method constructor arguments must be == 2!');}// 获得接口实例对象 for(var i = 0 , len = implInterfaces.length; i<len; i++ ){var instanceInterface = implInterfaces[i];// 判断参数是否是接口类的类型if(instanceInterface.constructor !== Interface){throw new Error('the implmented Interface constructor not be Interface Class');}// 循环接口实例对象里面的每一个方法for(var j = 0 ; j < instanceInterface.methods.length; j++){// 用一个临时变量 接受每一个方法的名字(注意是字符串)var methodName = instanceInterface.methods[j];// object[key] 就是方法if( !object[methodName] || typeof object[methodName] !== 'function' ){throw new Error("the method name '" + methodName + "' is not found !");}}}}// 二: 准备工作:// 1 实例化接口对象var CompositeInterface = new Interface('CompositeInterface' , ['add' , 'remove']);var FormItemInterface = new Interface('FormItemInterface' , ['update','select']);// 2 具体的实现类 var CompositeImpl = function(){//构造时即检测Interface.ensureImplements(this,CompositeImpl.prototype.implInterfaces);} // 3 定义要实现的接口CompositeImpl.prototype.implInterfaces = [CompositeInterface,FormItemInterface];// 4 实现接口的方法implements methods CompositeImpl.prototype.add = function(obj){alert('add');// do something ...}CompositeImpl.prototype.remove = function(obj){alert('remove');// do something ...}CompositeImpl.prototype.update = function(obj){alert('update');// do something ...}CompositeImpl.prototype.select = function(obj){alert('select');// do something ...}var c1 = new CompositeImpl();c1.add();
0 0
- javascript接口实现之鸭式辨型法
- JavaScript之接口实现
- javascript接口鸭式辨型法实现
- JavaScript-设计模式之接口的实现
- javascript实现接口
- 转 javascript实现接口
- Javascript实现接口
- JavaScript接口实现
- javascript鸭式辩型法实现接口
- javascript接口实现
- JavaScript学习之接口
- JavaScript建立接口的方式(一)之属性检测接口实现方式
- JavaScript建立接口的方式(二)之属性检测接口实现方式
- javascript模拟实现java接口
- JavaScript设计模式之接口
- 百度地图之调用javaScript api接口实现多点标注及显示提示信息
- Kotlin编程之接口和实现接口
- javascript 实现的CouchDB REST客户端接口
- 电子元件行业介绍及分析——ERP解决方案
- Android 隐藏标题栏
- python函数定义
- 从环境变量的配置到maven项目的编译、运行
- Android面试之----谈谈你对Java中Native关键字的认识!
- javascript接口实现之鸭式辨型法
- Jam的计数法
- iOS(CoreGraphics)画带箭头的框
- JavaScript-添加事件是与HTML里的结构相关的
- Performance of Using Keys in SELECT with FOR ALL ENTRIES
- RabbitMQ (三) 发布/订阅
- Android面试之----Android系统架构图及简单的系统架构介绍
- 路径
- vs添加行上下移快捷键