麻豆小视频在线观看_中文黄色一级片_久久久成人精品_成片免费观看视频大全_午夜精品久久久久久久99热浪潮_成人一区二区三区四区

首頁 > 開發 > JS > 正文

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,
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 欧产日产国产精品乱噜噜 | 成人福利视频在 | 少妇一级淫片高潮流水电影 | 高清在线国产 | 国产成人高清在线观看 | 欧美日本一 | avlululu| 狠狠操操 | 中文字幕天堂在线 | 国产精品久久久久免费视频 | 高颜值美女啪啪 | 最近中文字幕一区二区 | 国产伦乱视频 | 在线播放中文 | www亚洲成人| 国产黄色网页 | 136福利视频 | 国产一级毛片视频在线! | 高清国产午夜精品久久久久久 | 免费在线观看成人av | 亚洲精品午夜在线 | 得得啪在线 | 播色网 | 羞羞的视频在线免费观看 | 天天碰夜夜操 | 免费观看又色又爽又黄的崩锅 | 欧美成人免费小视频 | 国产91丝袜在线播放 | 涩涩操 | 国产精品自在线拍 | 欧美一级片一区 | 国产一区二区三区四区五区在线 | 亚洲性视频 | 成人午夜在线观看视频 | 日本在线播放一区二区三区 | 成人在线视频一区 | 在线亚洲欧美 | 精品一区二区久久久久久按摩 | 黑人日比 | 性高湖久久久久久久久aaaaa | 91成人一区二区三区 |