可以模拟接口,定义如下接口类: /** * 接口定义类 * @class Interface */ class Interface { constructor(name, methods) { // 参数合法性校验 if(arguments.length != 2){ throw new Error(`Interface constructor called with ${arguments.length} arguments,but expected exactly 2`); } this.name = name; // 接口定义数组合法性校验 this.methods = []; for(let i = 0, len = methods.length; i < len; i++) { if(typeof methods[i] !== 'string') { throw new Error('Interface constructor expects mothed names to be passed as a string'); } this.methods.push(methods[i]); } } /** * 接口合法性校验 * @method ensureImplements * @param {Object} instance */ ensureImplements(instance) { // 参数合法性校验 if(arguments.length != 1){ throw new Error(`Interface constructor called with ${arguments.length} arguments,but expected exactly 1`); } /* 校验传入的对象实例是否实现了指定接口 */ for(let i = 0, len = this.methods.length; i < len; i++) { let method = this.methods[i]; if(!instance[method] || typeof instance[method] !== 'function') { throw new Error(`Function Interface.ensureImplements:implements interface ${this.name} obj.mothed ${method} was not found`); } } } } 根据需求实现该接口类,这里实现了一个简单的测试接口类:let TestInterface = new Interface('Test', ['test1', 'test2']);上面的测试接口要求实例必须实现 test1 和 test2 两个方法。 测试接口类可以这么使用: let TestInstance = { test1: () => {} }; TestInterface.ensureImplements(TestInstance); 因为 TestInstance 没有实现 test2 接口,所以 ensureImplements 会抛出异常,这样就能实现简单的接口验证逻辑了。
可以模拟接口,定义如下接口类:
根据需求实现该接口类,这里实现了一个简单的测试接口类:
let TestInterface = new Interface('Test', ['test1', 'test2']);
上面的测试接口要求实例必须实现 test1 和 test2 两个方法。
测试接口类可以这么使用:
因为
TestInstance
没有实现test2
接口,所以ensureImplements
会抛出异常,这样就能实现简单的接口验证逻辑了。