javascript interface

系统 1812 0
我转载的啊:
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());

javascript interface


更多文章、技术交流、商务合作、联系博主

微信扫码或搜索:z360901061

微信扫一扫加我为好友

QQ号联系: 360901061

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描下面二维码支持博主2元、5元、10元、20元等您想捐的金额吧,狠狠点击下面给点支持吧,站长非常感激您!手机微信长按不能支付解决办法:请将微信支付二维码保存到相册,切换到微信,然后点击微信右上角扫一扫功能,选择支付二维码完成支付。

【本文对您有帮助就好】

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描上面二维码支持博主2元、5元、10元、自定义金额等您想捐的金额吧,站长会非常 感谢您的哦!!!

发表我的评论
最新评论 总共0条评论