国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

javascript設計模式 接口介紹

2024-05-06 14:21:34
字體:
來源:轉載
供稿:網友
這本書中第一個重要的內容就是接口。

大家對接口應該都不陌生,簡單的說接口就是一個契約或者規范。在強類型的面相對象語言中,接口可以很容易的實現。但是在javascript中并沒有原生的創建或者實現接口的方式,或者判定一個類型是否實現了某個接口,我們只能利用js的靈活性的特點,模擬接口。
在javascript中實現接口有三種方式:注釋描述、屬性驗證、鴨子模型。
note:因為我看的是英文書,翻譯水平有限,不知道有些詞匯如何翻譯,大家只能領會精神了。
1. 注釋描述 (Describing Interfaces with Comments)
例子:
代碼如下:
/*
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 和 implements關鍵字,但是需要將他們注釋起來,這樣就不會有語法錯誤。
這樣做的目的,只是為了告訴其他編程人員,這些類需要實現什么方法,需要在編程的時候加以注意。但是沒有提供一種驗證方式,這些類是否正確實現了這些接口中的方法,這種方式就是一種文檔化的作法。
2. 屬性驗證(Emulating Interfaces with Attribute Checking)
例子:
代碼如下:
/* 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;
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 江陵县| 齐齐哈尔市| 满洲里市| 尼玛县| 泸西县| 漳平市| 容城县| 平潭县| 九龙县| 拉萨市| 遵义市| 鹤庆县| 泽州县| 彩票| 牟定县| 都昌县| 冕宁县| 苏尼特右旗| 磐安县| 泾川县| 海林市| 禄丰县| 绍兴市| 金川县| 红桥区| 龙江县| 淄博市| 凌云县| 个旧市| 曲松县| 六枝特区| 泗洪县| 扎赉特旗| 长治市| 赞皇县| 进贤县| 新津县| 伊吾县| 武陟县| 洛扎县| 中方县|