cachaito
1/25/2014 - 1:12 PM

Pętla .forEach()

[].forEach.call(document.querySelectorAll('a'),
  function fn(elem) {
    console.log(elem.src);
  }
);

//forEach - anonimowa jako parametr w metodzie. Przykład z http://javascriptissexy.com/understand-javascripts-this-with-clarity-and-master-it/
var user = {
  tournament : "The Masters",
  data : [
    {name : "T. Woods", age : 37},
    {name : "P. Mickelson", age : 43}
  ],

  clickHandler: function () {
  // the use of this.data here is fine, because "this" refers to the user object, and data is a property on the user object.

    this.data.forEach(function(person) {
    // But here inside the anonymous function (that we pass to the forEach method), "this" no longer refers to the user object.
    // This inner function cannot access the outer function's "this"
   
      console.log ("What is This referring to? " + this); // [object Window]
   
      console.log (person.name + " is playing at " + this.tournament);
      // T. Woods is playing at undefined
      // P. Mickelson is playing at undefined
    }, user); //<-- jeśli nie podamy argumentu z this, zwróci powyższe
  }
}