如何用物件導向的思想來寫JavaScript,對於初學者應該是比較難的,我們經常用的JQuery其實也是用物件導向的思想去封裝的,今天我們來看看如何在Javascript中用Interface,在C#還是JAVA中都應該面向介面設計我們的程式,在C#和Java中都Interface這樣的關鍵字,但是JavaScript中沒有相應的機制,但是Javascript很靈活,我們可以用它的特性去模仿Interface,但是我們需要加入一些methods來做check的動作。
我們來看下一個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的時候發現並沒有去實現這個方法。