Example 1:

var array = [1,2,3,4,5];
array.forEach(function(item){
  console.log(item); -> 1,2,3,4..etc
  console.log(this); -> Global object
});

We should clean up this code: 

array.forEach(console.log); //Won't work 

var log = console.log
log("hello, world") //Won't work 

Why it does not work? 

We are taking the 'log' out of the console and we are invoking it directly in the global context. 
Console.log loses its context. When we invoke console.log we need it to be in the context of the context object. 
We are technically invoking console.log on the context object.

Example 2:

var personDatabase = {
  title = "Employees" 
  people: ["Nelson", "Foo"],
  print: function() {
   //'this' 
   this.people.forEach(function(person){
    //!= this 
    console.log(this.title +":" + person); // -> undefined: Nelson, undefined: Foo..etc
   }
  }
}

For each method strips away the context. 
The 'this' does not equal the 'this' in the forEach. 

Fix: 

1. Can use var that=this as a replacement to alias out the context; 
2. Can use the this args on the forEach method: people.forEach(...,this); We can pass the 'this' that was executed.

results matching ""

    No results matching ""