2

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 2

1

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.

3
  • So does it mean all that matters is the caller of the function and not the scope/block where it is called? Oct 5, 2017 at 12:47
  • 1
    In this case. Yes. Scope has nothing to do with the value of this (well, unless you use arrow functions which copy the value of this from the scope they are created in).
    – Quentin
    Oct 5, 2017 at 12:48
  • Got it. Will keep this in mind. this is not that easy ;) Oct 5, 2017 at 12:57
0

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.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.