kellymandem
kellymandem

Reputation: 1769

Why is JavaScript producing "this" output?

I have been using JavaScript for some time now, but this particular piece of code has perplexed me a bit.

Why is this the output of the following piece of code

length = 10;
function func() {
  console.log(this.length);
}

var obj = {
  length: 5,
  thisFunc: function(func) {
    func();
    arguments[0]();
  }
};

obj.thisFunc(func, 3);

producing

10
2

and not

10
5

or at least

10
10

Could somebody explain to me where the value 2 is coming from and what I missed when it comes to this in this(no pun intended) particular instance?

Upvotes: 1

Views: 53

Answers (1)

Tushar Shahi
Tushar Shahi

Reputation: 20441

In the first case, it is same as doing console.log(this.length) anywhere in the global scope. So it will be 10 as you understand.

As mentioned in the comments, arguments object is an array-like object which has a property length.

You can use arguments.length to count how many arguments the function was called with`

In the above quote, the called with part is important.

In the second case, the function is run in the context of the arguments object. You know that the value of this inside a function depends on how it is invoked. Here this is the arguments object, whose length is 2.

length = 10;
function func() {
  console.log(this.length);
}

var obj = {
  length: 5,
  thisFunc: function(func) {
    
    func();
    arguments[0]();
    console.log(arguments.length);
  }
};

obj.thisFunc(func, 3);
console.log(this.length);

Upvotes: 2

Related Questions