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