0

Why is it that the 'this' keyword in the printActions function below can access the 'actions' array, but the 'this' keyword in the anonymous function inside the forEach loop, cannot access the 'first' name property?

var person = {
    first: "Steve",
    actions: ['run', 'swim', 'bike'],
    printActions: function () {
         this.actions.forEach(function (action) {
            var str = this.first + " likes to " + action;
            console.log(str);

        }); //end forEach
    }//end printActions function

};// person object
person.printActions();
Chris Mazzochi
  • 169
  • 1
  • 9
  • 2
    Because the `this` is set on per-call basis*, and in this very case you don't help runtime understand what context that function belongs to. – zerkms Jul 24 '17 at 21:12
  • Two simple solutions: (1) Use arrow function syntax for the `forEach` callback, or (2) append `.bind(this)` to the closing brace of that function. – trincot Jul 24 '17 at 21:15
  • See [this answer](https://stackoverflow.com/questions/41385835/invocation-context-and-execution-context-in-javascript-are-we-talking-of-th/41386097#41386097) that I posted some time ago. – Scott Marcus Jul 24 '17 at 21:15
  • Excellent thanks all. – Chris Mazzochi Jul 24 '17 at 21:18

0 Answers0