时间:2021-07-01 10:21:17 帮助过:19人阅读
继承了这个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的时候发现并没有去实现这个方法。