随笔 - 223  文章 - 0 评论 - 6 阅读 - 39万
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

什么是接口?

接口提供了一种用以说明一个对象应该具有哪些方法和手段。

在面向对象的javascript中,接口有些什么作用呢?既定的一批接口具有自我描述性,并能促进代码重用。接口可以告诉程序员一个类实现了哪些方法,从而帮助其使用这个类。

在C#还是JAVA中都应该面向接口设计我们的程序,在C#和Java中都Interface这样的关键字,但是JavaScript中没有相应的机制,但是Javascript很灵活,我们可以用它的特性去模仿Interface。

 

使用 Interface.js

复制代码
var Interface = function(name, methods) {
    if(arguments.length != 2) {
        throw new Error("请确认要检查的接口所传的参数是否正确,例如:var Person = new Interface('Person', ['GetName','GetAge']);");
    }
    if(methods.length == 0){
        throw new Error("要检查的接口的方法名不能为空");
    }
    this.Name = name;
    this.Method = [];
    for(var i = 0; i < methods.length; i++) {
        if(typeof methods[i] !== 'string') {
            throw new Error("方法名不是字符串");
        }
        this.Method.push(methods[i]);
    }
}
/*static method in interface*/
Interface.ensureImplement = function(object) {
    if(arguments.length < 2) {
        throw new Error("没有接口或实例");
    }

    for(var i = 1; i < arguments.length; i++) {
        var interface1 = arguments[i];
        if(interface1.constructor !== Interface) {
            throw new Error("参数不是接口");
        }
        for(var j = 0; j < interface1.Method.length; j++) {
            var method = interface1.Method[j];
            if(!object[method] || typeof object[method] !== 'function') {
                throw new Error("您的实例没有实现接口:\t" + method);
            }
        }
    }
}
复制代码

 

案例:

复制代码
// 封装接口的类,假如该类中实现的  add del 2个方法
function Peson(){}
Peson.prototype.add = function(){
    console.log('新增接口');
}
Peson.prototype.del = function(){
    console.log('删除接口');
}

//在你使用该类的方法的时候先去检查你要用到的方法是否存在
var peson = new Peson();
//Interfaces
var check = new Interface('check',['add', 'del']);
//检查你要用到的方法是否存在,如果你要用的方法没有实现,会抛出错误提示
Interface.ensureImplement(peson, check);
//使用接口
peson.add();
peson.del();
复制代码

使用es6 的class 也是可以的

复制代码
class Peson{
    add(){
        console.log('新增接口');
    }
    del(){
        console.log('删除接口');
    }
}
//在你使用该类的方法的时候先去检查你要用到的方法是否存在
var peson = new Peson();
//Interfaces
var check = new Interface('check',['add', 'del']);
//检查你要用到的方法是否存在,如果你要用的方法没有实现,会抛出错误提示
Interface.ensureImplement(peson, check);
//使用接口
peson.add();
peson.del();
复制代码

 

posted on   浅唱年华1920  阅读(20949)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示