当前位置:首页 > JavaScript

实现接口js

2026-03-01 12:16:02JavaScript

在 JavaScript 中实现接口

JavaScript 本身没有内置的接口(Interface)概念,但可以通过多种方式模拟接口的行为。以下是几种常见的实现方法:

使用 TypeScript 的接口

TypeScript 是 JavaScript 的超集,直接支持接口语法:

interface MyInterface {
  method1(): void;
  method2(param: string): number;
}

class MyClass implements MyInterface {
  method1() {
    console.log("Method1 called");
  }

  method2(param: string) {
    return param.length;
  }
}

在纯 JavaScript 中模拟接口

可以通过运行时检查来模拟接口行为:

function implementInterface(obj, interfaceDefinition) {
  for (const method in interfaceDefinition) {
    if (typeof obj[method] !== 'function') {
      throw new Error(`Missing implementation for ${method}`);
    }
  }
  return true;
}

const myInterface = {
  method1: function() {},
  method2: function(param) {}
};

class MyClass {
  method1() {
    console.log("Method1 called");
  }

  method2(param) {
    return param.length;
  }
}

implementInterface(new MyClass(), myInterface);

使用鸭子类型

JavaScript 采用鸭子类型(Duck Typing),只需确保对象具有接口要求的方法即可:

function requiresInterface(obj) {
  if (!obj.method1 || !obj.method2) {
    throw new Error("Object doesn't implement required interface");
  }
}

const myObject = {
  method1: () => console.log("Method1"),
  method2: (param) => param.length
};

requiresInterface(myObject);

使用 Symbol 定义接口

通过 Symbol 可以创建唯一的接口标识符:

实现接口js

const MyInterface = Symbol('MyInterface');

function implementInterface(obj) {
  obj[MyInterface] = true;
  return obj;
}

function isImplemented(obj) {
  return !!obj[MyInterface];
}

const myObj = implementInterface({
  method1: () => {}
});

console.log(isImplemented(myObj)); // true

选择哪种方法取决于具体需求。TypeScript 提供了最完整的接口支持,而纯 JavaScript 方案则更灵活但需要手动实现类型检查。

标签: 接口js
分享给朋友:

相关文章

js实现图片预览

js实现图片预览

使用FileReader API实现图片预览 通过FileReader对象读取用户选择的图片文件并显示预览: const input = document.getElementById('image…

js实现拷贝

js实现拷贝

实现文本拷贝 使用 document.execCommand 方法(已废弃但兼容性较好): function copyText(text) { const textarea = document…

js实现二叉树

js实现二叉树

二叉树的基本概念 二叉树是一种树形数据结构,每个节点最多有两个子节点,分别称为左子节点和右子节点。二叉树的常见操作包括插入、删除、遍历等。 二叉树的节点定义 在JavaScript中,二叉树的节点可…

js实现变形

js实现变形

使用 CSS 和 JavaScript 实现元素变形 在 JavaScript 中实现变形效果通常结合 CSS 的 transform 属性,通过动态修改该属性实现元素的旋转、缩放、倾斜或平移。 基…

js实现驼峰

js实现驼峰

实现驼峰命名的几种方法 使用正则表达式和字符串替换 通过正则表达式匹配字符串中的特定模式(如下划线或短横线),并将其后的字母转换为大写,同时移除分隔符。 function toCamelCase(s…

链表实现js

链表实现js

链表的基本概念 链表是一种线性数据结构,由一系列节点组成,每个节点包含数据和一个指向下一个节点的指针(单向链表)或两个指针(双向链表)。与数组不同,链表在内存中非连续存储,插入和删除操作更高效,但随机…