0

I'm at the beginning of my JS journey and I have a problem with uderstanding what is going on inside this code:

function createMessages() {
   var i = 0, messagesFuncs = [];
   for (i = 0; i <= 3; i++) {
      messagesFuncs.push(function () { //this is a closure
           console.log(i);
      });
   }
   return messagesFuncs; 
}



messages = createMessages();
messages[0](); //4
messages[1](); //4
messages[2](); //4

I'm curious why in all cases of calling messages the result is 4 and why not the numbers from an messagesFunc array in ascending order like: 1, 2, 3?

Question 2:

a = 10;
(function() {
var a = 5;

var x = {
    a: 3,
    method: function foo(arg1, arg2) {
        console.log(this.a);
        console.log(arg1);
        console.log(arguments.slice(1,2));
    }
};
var foo = x.method;
foo(1, 2); //10, 1 
x.method(1, 2); //3,1
})();

Why those two calls aren't the same ? why in first case this.a is asigned to 10 and not 5 the 10 is outside the function so why this keyword is not using the variable which is declared inside function ?

In second call I am assuming that when we calling the x.method( - object property ) directly the this keyword is operating only inside our object (x) ?

I am looking forward to any response and guidance. Cheers

Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
wkf_fan
  • 13
  • 4
  • 2
    Please restrict your questions to exactly one question. Question 1: [check this out](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example). Question 2: [check this one](http://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback). – Mike Cluck Oct 14 '16 at 17:34
  • but I still don't get it why this is happening. – wkf_fan Oct 15 '16 at 14:37
  • Read the questions I linked to. You're calling that function in the global context so it's using the global `a` – Mike Cluck Oct 15 '16 at 17:19

0 Answers0