Lodash mixin在JavaScript Class中不起作用

时间:2017-02-11 00:05:18

标签: javascript ecmascript-6 lodash mixins

我正在使用lodash的_.mixin_.chain来链接我的自定义函数。当代码在类之外时,代码工作正常,如下所示:

工作代码:

     function start(data, param1, param2) {
      _.mixin({
        'someFunc': this.someFunc,
        'anotherFunc': this.anotherFunc
      })

      // Chaining directly works
      _.someFunc(data, param1)
       .anotherFunc(param2)

     // Using chain works
     return _.chain(data)
      .someFunc(param1)
      .anotherFunc(param2)
     }

     function someFunc(data, param) {
       return data;
     }

     function anotherFunc(data, param) {
       return data + param;
     }

当我在一个类中使用代码时,它开始抛出一个TypeError: _.chain(...).someFunc is not a function

  import * as _ from 'lodash';

  class MyClass {
    constructor() {
      //.... code
    }

    start(data, param1, param2) {

      // Does not work
      _.mixin({
         'someFunc': this.someFunc,
         'anotherFunc': this.anotherFunc
      })

      // Does not work
      _.someFunc(data, param1)
       .anotherFunc(param2)

      // Also does not work
      return _.chain(data)
       .someFunc(param1)
       .anotherFunc(param2)

     // Using them separately works:
     let result = _.someFunc(param1);
     let result2 = _.anotherFunc(param2);

    }

    someFunc(data, param) {
      return data;
    }

    anotherFunc(data, param) {
      return data + param;
    }


  }

如果有人能够了解为何会发生这种情况,我真的很感激。

1 个答案:

答案 0 :(得分:0)

_.someFunc(data, param1)
 .anotherFunc(param2)

someFunc不会返回lodash包装器对象,因此您无法在返回值上调用anotherFunc