I came across an Javascript Example but not quite satisfied with the justification or rather confused on scope of this
inside function. See the example below:
var length = 10;
function fn() {
console.log(this.length);
}
var obj = {
length: 5,
method: function(fn) {
fn();
arguments[0]();
}
};
obj.method(fn, 1);
First time 10
is logged which is understandable since it is called from global scope. However second time 2
is logged which sort of confused me. I look for an answer and this is what I got -
We know that we can access any number of arguments in a JavaScript function using the arguments[] array.
Hence arguments0 is nothing but calling fn(). Inside fn now, the scope of this function becomes the arguments array, and logging the length of arguments[] will return 2
Does anyone has a better answer to this one?