繼承了這個(gè)Interface就必須要實(shí)現(xiàn)這個(gè)Interface中定義的方法(方法簽名)
//JavaScript 現(xiàn)在還做不到方法的簽名的約束
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,我們現(xiàn)在的做法是用來比較一個(gè)Instance中的方法名在接口中是否定義了。
我先定義一個(gè)接口(2個(gè)參數(shù)),第二個(gè)參數(shù)是接口中的方法名。Check方法用簡單的2層for循環(huán)來做比較動(dòng)作。
我們來看下如何去用這個(gè)接口:
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方法,在執(zhí)行的時(shí)候就會(huì)出錯(cuò)。在ensureImplement的時(shí)候發(fā)現(xiàn)并沒有去實(shí)現(xiàn)這個(gè)方法。
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問題請及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com