3

I think this is more of a javascript question than an angular question, but context was angular, so keeping it there. Basically I am trying to call the doSomething method. It looks like lodash's ._forEach is creating its own scope, so I can't access var service using this, because that refers to the loop here.

So, what's the best way for me to call doSomething from where it is in the code below (inside the forEach)?

'use strict';

angular.module('app').service('fooService', function()
{

    var service = {
        barMethod: function(arrayOfObjects){
            //this.doSomething(); - this works if not commented out, 
            //but I need it from within loop
            _.forEach(arrayOfObjects, function (ob) {
                this.doSomething();
            });

        },

        doSomething: function(){
            //do something
        },

    };

    return service;
});
VSO
  • 11,546
  • 25
  • 99
  • 187

1 Answers1

4

try this

var service = {
    barMethod: function(arrayOfObjects){
          var self = this
        _.forEach(arrayOfObjects, function (ob) {
            self.doSomething();
        });

    },

    doSomething: function(){
        //do something
    },

};
aseferov
  • 6,155
  • 3
  • 17
  • 24
  • Upvoted because I know that works without trying it, but wondering if there is some other way. I will accept answer later if not. Ty. (edit: And I confirmed that it works) – VSO May 25 '16 at 19:01
  • check this http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback maybe it helps you find answer – aseferov May 25 '16 at 19:07
  • 1
    Couldn't you use an arrow function then the self hack would not be needed. `_.forEach(arrayOfObjects, ob => {this.doSomething();})`. – AndrewRMillar Nov 20 '18 at 08:58