Saturday, April 13, 2024
 Popular · Latest · Hot · Upcoming
122
rated 0 times [  124] [ 2]  / answers: 1 / hits: 6973  / 9 Years ago, tue, december 22, 2015, 12:00:00

Relating to the following mock code (_ relates to the lodash library):



var containerFunction = function () {
var opts = {data: value};
_.map(lines, functionForEach);
}

var functionForEach = function (line) {
Do something for each line passed in from the maps function.
Need to access opts in this scope.
return value;
}


The argument line is received from the map function, but what would be the best way of passing the opts argument to the functionForEach function while keeping the rough pattern above (if possible).



I thought something like:



_.map(lines, functionForEach(opts))


or something similar might work but obviously doesn't.



Any suggestions?


More From » scope

 Answers
3

You have three alternatives:




  1. Put functionForEach inside containerFunction. If you are not going to use functionForEach elsewhere, this makes the most sense.


  2. Write it as:



    var containerFunction = function () {
    var opts = {data: value};
    _.map(lines, function(elt) { return functionForEach(elt, opts); });
    }

    var functionForEach = function (line, opts) {
    Do something for each line passed in from the maps function.
    Need to access opts in this scope.
    return value;
    }






  1. If you must, pass opts as the third (thisArg) argument to _.map and access it using this inside functionForEachvar.


[#32042] Monday, December 21, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
brynneg

Total Points: 205
Total Questions: 111
Total Answers: 112

Location: Djibouti
Member since Wed, Dec 8, 2021
2 Years ago
;