javascript接口实现之鸭式辨型法

本文介绍了一种使用JavaScript自定义接口类来确保对象实现特定方法的机制。通过具体示例展示了如何定义接口、实现接口以及进行实现检查的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//接口类
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]);
	}
}

// 检测对象是否实现相应接口中定义的方法
// 如果检验通过 不做任何操作 不通过:浏览器抛出error
Interface.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();	

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值