JavaScript接口實現代碼 (Interfaces In JavaScript)
2024-09-06 12:45:49
供稿:網友
在實際中,我們可以在注釋中定義好接口,在實際的代碼中予以實現
比如:
代碼如下: /*
interface Composite {
function add(child);
function remove(child);
function getChild(index);
}
interface FormItem {
function save();
}
*/
var CompositeForm = function(id, method, action) { // implements Composite, FormItem
...
};
// Implement the Composite interface.
CompositeForm.prototype.add = function(child) {
...
};
CompositeForm.prototype.remove = function(child) {
...
};
CompositeForm.prototype.getChild = function(index) {
...
};
// Implement the FormItem interface.
CompositeForm.prototype.save = function() {
...
};
實現接口的程序員是否將這些接口都實現了呢?我們沒辦法保證!因為這里沒有任何辦法去檢查是否都實現了
我們需要一個檢查是否實現了接口的機制,可以這樣:
代碼如下: /*
interface Composite {
function add(child);
function remove(child);
function getChild(index);
}
interface FormItem {
function save();
}
*/
var CompositeForm = function(id, method, action) {
this.implementsInterfaces = ['Composite', 'FormItem'];
...
};
...
function addForm(formInstance) {
if(!implements(formInstance, 'Composite', 'FormItem')) {
throw new Error("Object does not implement a required interface.");
}
...
}
// The implements function, which checks to see if an object declares that it
// implements the required interfaces.
function implements(object) {
for(var i = 1; i < arguments.length; i++) { // Looping through all arguments
// after the first one.
var interfaceName = arguments[i];
var interfaceFound = false;
for(var j = 0; j < object.implementsInterfaces.length; j++) {
if(object.implementsInterfaces[j] == interfaceName) {
interfaceFound = true;
break;
}
}
if(!interfaceFound) {
return false; // An interface was not found.
}
}
return true; // All interfaces were found.
}
這種方法讓程序員在寫的時候注明實現了哪些接口: this.implementsInterfaces = ['Composite', 'FormItem']; 在調用的時候使用implements方法來判斷是否實現了,理論上可行,很有可能寫上了實現了'Composite'接口,但是代碼里卻并沒有add方法!因此,我們需要檢驗實現接口的類是否包含了接口里的方法!所以,接口必須從注釋中解放出來:
代碼如下: // Interfaces.
var Composite = new Interface('Composite', ['add', 'remove', 'getChild']);
var FormItem = new Interface('FormItem', ['save']);
// CompositeForm class
var CompositeForm = function(id, method, action) { // implements Composite, FormItem
...
};
...
function addForm(formInstance) {
Interface.ensureImplements(formInstance, Composite, FormItem);
// This function will throw an error if a required method is not implemented,