annotate函数

抽取出依赖注入的函数

annotate.js

function annotete(...args) {
  if (args.length === 1 && isArray(args[0])) {
    args = args[0];
  }

  args = [ ...args ];

  const fn = args.pop();

  fn.$inject = args;

  return fn;
}

annotate.test.js

const fn = function(a, b) {
  return null;
};
annotete('aa','bb',fn);
/**
 * should set $inject property on the last argument
 * 将最后一个参数设置一个$inject的值,且这个值是前面参数构造的数组
 */
expect((fn).$inject).to.eql([ 'aa', 'bb' ]);
/**
 * should return the function
 * 调用以后返回这个参数的值
 */
expect(annotate('aa', 'bb', fn)).to.equal(fn);
/**
 * should inject using array args
 * 可以使用数组参数来注入
 */
expect(annotate([ 'aa', 'bb', fn ])).to.equal(fn);


class Foo {
    constructor(a, b) { }
}
expect(annotate('aa', 'bb', Foo).$inject).to.eql([ 'aa', 'bb' ]);
expect(annotate('aa', 'bb', Foo)).to.equal(Foo);

const fn1 = (a, b) => a + b;
expect(annotate('aa', 'bb', fn1).$inject).to.eql([ 'aa', 'bb' ]);
expect(annotate('aa', 'bb', fn1)).to.equal(fn1);

版权声明:著作权归作者所有。

thumb_up 0 | star_outline 0 | textsms 0