与 stampit 2 的接口

Interfaces with stampit 2

interface section of 'Programming javascript applications' you can implement interfaces with stampit所述。当从例子中减少不必要的东西时,我最终得到这样的东西:

const fooBarInterface = 
    stampit()
        .methods(
            {
                foo: () => {
                    throw new Error('connect not implemented'); 
            },
                bar: () => {
                    throw new Error('save not implemented');
            }
        }
    )

接口定义摘录:

If your class claims to implement an interface, all methods defined by that interface must appear in its source code before the class will successfully compile.

现在开始使用界面

const fooBarImplementation = 
    stampit()
        .compose(fooBarInterface)
        .methods(
            {
                foo: () => {
                    // implement me
                }
            }
        }
    )

现在,当从 stamp 组合对象时,应该会出现错误,因为 bar 不是由 fooBarImplementation 实现的。它不是,而且我担心很难得到这样的东西,因为根本没有编译。

所以,我的问题是:我做错了吗,或者这是 Eric Elliott 所说的半生不熟的东西 'Interface'?

您创建的 module 太棒了!你真的很了解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