Why the output is 2 during second fn function call?

Viewed 847

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?

2 Answers

You call arguments[0]();

The value of this is therefore the same as arguments.

The arguments are: fn, 1

There are 2 of them.

arguments.length is therefore 2.

Arguments is an array-like object. When you invoke arguments[0](), the function that returns this.length is sitting inside the array-like arguments object. In that context, the keyword this refers to the arguments object.

arguments: [function fn() { return this.length; }, 1]
arguments[0](); // returns 2;

Here's a different example to help illustrate my point:

const arr = [1, 2, function() { return this.length }];
console.log(arr[2]()); // 3

The third item in the array is a function that, when invoked, returns the length of the array. That is similar to writing arr.length.

Related