正如界面段 of 'Programming javascript ‘中所提到的,您可以使用踩踏实现接口。在减少示例中不必要的内容时,我的结果是这样的:
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
}
}
}
)现在,当从邮票组合一个对象时,应该会出现一个错误,因为bar不是由fooBarImplementation实现的。事实并非如此,而且我担心这样的事情很难实现,因为根本就没有编译。
所以,我的问题是:我是做错了吗,还是这个半烤的东西,埃里克·埃利奥特称之为“界面”?
发布于 2016-04-13 07:58:52
您创建的模块非常棒!你真的很了解踩踏。
虽然,在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
https://stackoverflow.com/questions/33743568
复制相似问题