javascript interface

我转载的啊:
function Interface(name, methods)
{
if(arguments.length != 2) {
throw new Error("接口构造函数含" + arguments.length + "个参数, 但需要2个参数.");
}
this.name = name;
this.methods = [];
if(methods.length < 1) {
throw new Error("第二个参数为空数组.");
}
for(var i = 0, len = methods.length; i < len; i++) {
if(typeof methods[i][0] !== 'string') {
throw new Error("接口构造函数第一个参数必须为字符串类型.");
}
if(methods[i][1] && typeof methods[i][1] !== 'number') {
throw new Error("接口构造函数第二个参数必须为整数类型.");
}
if(methods[i].length == 1) {
methods[i][1] = 0; // 只有一个方法名称,没有参数,所以……
}
this.methods.push(methods[i]);
}
};

Interface.registerImplements = function(object) {

if(arguments.length < 2) {
throw new Error("接口的实现必须包含至少2个参数."); // 类名和方法数组
}

for(var i = 1, len = arguments.length; i < len; i++) {
var interface = arguments[i];
if(interface.constructor !== Interface) {
throw new Error("从第2个以上的参数必须为接口实例.");
}
for(var j = 0, methodsLen = interface.methods.length; j < methodsLen; j++) {
var method = interface.methods[j][0];
if(!object[method] || typeof object[method] !== 'function' || object[method].getParameters().length != interface.methods[j][1]) {
throw new Error("接口的实现对象不能执行" + interface.name + "的接口方法" + method + ",因为它找不到或者不匹配.");
}
}
}
};

Function.prototype.getParameters = function() {

var str = this.toString();
var paramString = str.slice(str.indexOf('(') + 1, str.indexOf(')')).replace(/\s*/g,''); //取得参数字符串
try
{
return (paramString.length == 0 ? [] : paramString.split(','));
}
catch(err)
{
throw new Error("函数不合法!");
}
}

var Person = new Interface("Person", [["getName", 0], ["setName", 1]]);
function Man()
{
this.name = "";
Interface.registerImplements(this, Person);
}
Man.prototype.getName = function() {
return this.name;
};
Man.prototype.setName = function(name) {
this.name = name;
};
var man = new Man();
man.setName("Leepy");
alert(man.getName());

function SchoolBoy(classNo, post)
{
Man.call(this);
this._chassNo = classNo;
this._post = post;
}
SchoolBoy.prototype = new Man();
SchoolBoy.prototype.getName = function() {
return "Mr " + this.name;
}
SchoolBoy.prototype.setName = function(name) {
this.name = name + "'s";
}
var schoolboy = new SchoolBoy("三年二班", "班长");
schoolboy.setName("周杰伦");
alert(schoolboy.getName());
:o
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值