Search code examples
javascriptnode.jslodash

_.bindAll(this) not working after updating to [email protected]


After finding some npm audit vulnerabilities I updated lodash to version 4.17.15.

After the update _.bindAll(this); is not woking in my modules.

How I can fix this? Is there any workaround for fixing this in my entire codebase.

Thanks.


Solution

  • Looks to me as if you're upgrading from version 3.10.1 or earlier: that appears to be when lodash stopped making the second parameter of bindAll optional. See the difference between the current docs and the 3.10.1 docs.

    Fortunately if we look at the old source code it's easy to see how it was handling the optional methodNames before: it was using _.functions() to provide the list if it was omitted.

    var bindAll = restParam(function(object, methodNames) {
      methodNames = methodNames.length ? baseFlatten(methodNames) : functions(object);
      // ...
    

    The least invasive solution is going to be to monkey-patch lodash to restore that optional logic . That way you don't need to change any of your existing code. Something like this perhaps. You'd want to put this in a script tag immediately following your lodash script tag.

    (function(_) {
      var bindAll = _.bindAll;
      _.bindAll = function(object, methodNames) {
        if(typeof methodNames==='undefined') methodNames = _.functions(object);
        return bindAll(object, methodNames);
      };
    })(_);
    

    However, keep in mind that monkey patching can be dangerous, since you are altering the native functionality of lodash.

    This means that the monkey patch could cause problems during a future lodash upgrade, and it could also be confusing for other developers working on the code in the future.