【问题标题】:Lodash mixin not working in JavaScript ClassLodash mixin 在 JavaScript 类中不起作用
【发布时间】:2017-06-29 11:10:51
【问题描述】:

我正在使用 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;
    }


  }

如果有人能深入了解为什么会发生这种情况,我将不胜感激。

【问题讨论】:

    标签: javascript ecmascript-6 lodash mixins


    【解决方案1】:
    _.someFunc(data, param1)
     .anotherFunc(param2)
    

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

    【讨论】:

    • return _.chain(data).someFunc(param1).anotherFunc(param2).value() 怎么样?链方法不应该链接自定义函数吗?为什么这会在课堂外而不在课堂内起作用?
    • 是的,chain 确实链接了自定义函数。 return ... 行对我来说很好,你能提供更多关于你的错误的信息吗?你运行的是什么版本的 lodash?
    • Lodash 4.17.2。我将它与 webpack/angular 一起使用。是的,链方法在课堂之外对我有用。在类内部使用时,它会中断。
    • 奇怪。除了这个答案中给出的内容之外,你的两个例子对我来说都没有错误。也许_.chain 被覆盖了? _.chain(data).value() 返回什么?
    • 很奇怪。我不确定我在这里缺少什么。 _.chain(data).value() 返回 undefined 但仅在类内部。
    猜你喜欢
    • 1970-01-01
    • 2018-08-27
    • 2016-12-02
    • 2018-05-28
    • 1970-01-01
    • 2016-08-04
    • 2019-04-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多