Does lodash filter function use context?

I looked through the lodash filter documentation and it is unclear if the third parameter is context.

I am using the cytoscape (dagre) plugin and it seems to pass this as 3 arguments. When I pause execution until the filter method is called, this determined. But inside the call to this there is undefined.

I looked through the underscore filter documentation and it seems the third argument is being considered context. So I guess that the plugin originally used the underscore, and then maybe changed to lodash. The project I'm working on uses lodash.

I cannot understand why this is null at this point of my can. This may be project specific, but I just want to be sure of the third lodash filter parameter.

Is the lodash filter definition exactly the same as the underscore filter? This is not like documentation.

+5
source share
2 answers

Unfortunately, the lodash filter method , unlike the underscore filter method , does not provide a parameter for the context argument, since it takes only two arguments:

Arguments

  • collection (Array | Object): collection for iteration.
  • [predicate = _. identity] (Function): function called for each iteration.

What you can do is use the .bind() method to bind the callback function to the desired context object, e.g.

 _.filter(array, callback.bind(context)); 

Note:

Note that Javascript has its own Array#filter() method , which already provides this option.

+2
source

Well, you can always define your own context using Function.prototype.bind .

 _.filter([โ€ฆ], function (o) { console.log(this.id); //100 //than return something based on o return o.active }.bind({id: 100}) ); 

Doc on mdn

+3
source

Source: https://habr.com/ru/post/1273991/


All Articles