[英]Interfaces with stampit 2
如“ 编程javascript应用程序 ”的接口部分所述 ,您可以使用Stampit实现接口。 当减少示例中不必要的内容时,我最终得到这样的结果:
const fooBarInterface =
stampit()
.methods(
{
foo: () => {
throw new Error('connect not implemented');
},
bar: () => {
throw new Error('save not implemented');
}
}
)
接口定义摘录:
如果您的类声称要实现一个接口,则在成功编译该类之前,该接口定义的所有方法必须出现在其源代码中。
所以现在使用界面
const fooBarImplementation =
stampit()
.compose(fooBarInterface)
.methods(
{
foo: () => {
// implement me
}
}
}
)
现在,当从图章组成对象时,应该出现错误,因为fooBarImplementation没有实现bar。 并非如此,我担心很难实现这样的目标,因为根本没有编译。
因此,我的问题是:我做错了吗?还是Eric Elliott所说的“半熟东西”?
您创建的模块很棒! 你真的很了解stampit。
尽管在JavaScript中,我还是建议您走另一条路。 即,检查方法是否存在。
if (obj.bar) kangaroo.bar();
并完全删除fooBarInterface
。 但是,如果您在创建对象时需要检查方法的存在,则应与模块类似。
var ValidateFooBar = stampit()
.init(function() {
if (!_.isFunction(this.foo)) throw new Error('foo not implemented');
if (!_.isFunction(this.bar)) throw new Error('bar not implemented');
});
并使用它:
const fooBarImplementation = stampit()
.compose(ValidateFooBar)
.methods({
foo: function() {
// implement me
}
});
将抛出: Error: bar not implemented
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.