我们来看下一个interface的作用:
继承了这个interface就必须要实现这个interface中定义的方法(方法签名)
//javascript 现在还做不到方法的签名的约束
var interface = function (name, methods) {
if (arguments.length != 2) {
throw new error(the interface length is bigger than 2);
}
this.name = name;
this.method = [];
for (var i = 0; i < methods.length; 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 < 2) {
throw new error(there is not interface or the instance);
}
for (var i = 1; i < arguments.length; i++) {
var interface1 = arguments[i];
if (interface1.constructor !== interface) {
throw new error(the argument is not interface);
}
for (var j = 0; j < interface1.method.length; 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的时候发现并没有去实现这个方法。
