javascript无原生interface,但可通过运行时检查实现接口契约:定义含methodnames/propertynames的契约对象,用implements函数校验实例是否具备指定方法和属性,支持构造时自动校验或proxy动态拦截。

JavaScript 本身没有原生的接口(interface)概念,class 语法也不支持像 TypeScript 那样在编译期校验接口契约。但你可以用运行时检查的方式,在 class 构造或方法调用前,主动验证实例是否满足某个“接口契约”——即是否具备指定的方法、属性、类型或行为特征。
定义接口契约(用普通对象描述)
把接口看作一个结构契约,用 plain object 描述它需要哪些成员(方法或属性),以及可选的类型约束:
- methodNames:必需的方法名数组
- propertyNames:必需的属性名数组(可选)
- methodSignatures:更进一步,检查方法是否为函数(可选)
例如,定义一个 Drawable 接口契约:
const DrawableContract = {
methodNames: ['draw', 'getBounds'],
propertyNames: ['id']
};
编写校验函数(运行时检查)
写一个通用函数,在实例创建后或使用前执行检查:
在 Java 中初始化和管理阿里云 SDK客户端。包括单例模式、线程安全、endpoint 与 region 配置、VPC 终端节点、同步与异步等。
function implements(contract, instance) {
if (typeof instance !== 'object' || instance === null) {
throw new TypeError('Instance must be a non-null object');
}
<p>for (const method of contract.methodNames || []) {
if (typeof instance[method] !== 'function') {
throw new Error(<code>Missing required method: ${method}</code>);
}
}</p><p>for (const prop of contract.propertyNames || []) {
if (!(prop in instance)) {
throw new Error(<code>Missing required property: ${prop}</code>);
}
}</p><p>return true;
}</p>
使用方式:
class Circle {
constructor(id) {
this.id = id;
}
draw() { console.log('drawing circle'); }
// 忘了实现 getBounds → 校验会报错
}
<p>const c = new Circle('c1');
implements(DrawableContract, c); // 报错:Missing required method: getBounds</p>
在 class 构造函数中自动校验
让校验成为 class 的一部分,增强契约意识:
class DrawableBase {
constructor() {
// 子类必须调用 super(),然后手动校验自身
if (new.target === DrawableBase) {
throw new TypeError('DrawableBase is abstract');
}
}
<p>static ensureImplements(instance, contract) {
implements(contract, instance);
}
}</p><p>class Rect extends DrawableBase {
constructor(id, width, height) {
super();
this.id = id;
this.width = width;
this.height = height;
}
draw() { /<em> ... </em>/ }
getBounds() { return { w: this.width, h: this.height }; }</p><p>// 构造完成立即校验
init() {
DrawableBase.ensureImplements(this, DrawableContract);
return this;
}
}</p><p>// 使用:
const r = new Rect('r1', 100, 50).init(); // ✅ 通过校验</p>
进阶:配合 Proxy 实现访问时动态校验
若想在每次调用方法/读取属性时都检查(比如调试阶段),可用 Proxy 包裹实例:
function enforceContract(instance, contract) {
return new Proxy(instance, {
get(target, key) {
if (contract.methodNames?.includes(key) && typeof target[key] !== 'function') {
throw new Error(`Expected function for ${key}, got ${typeof target[key]}`);
}
if (contract.propertyNames?.includes(key) && !(key in target)) {
throw new Error(`Missing required property: ${key}`);
}
return target[key];
}
});
}
<p>const safeRect = enforceContract(new Rect('r2', 80, 40), DrawableContract);
safeRect.draw(); // ✅
safeRect.toString(); // ✅ 不在校验范围内,放行
</p>
注意:Proxy 带来性能开销,仅建议用于开发/测试环境。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










