Send function to call() as argument

55 Views Asked by At

here in this example

function a() { console.log(this.x); }

var x = 10;
a.x = 20;

a.call(a);

The result is 20

Why does this happen?

I know in call method we can send object but here send a function? can we do that? and why does a.x work?

1

There are 1 best solutions below

0
ABR On

The call() method can be used to invoke a function with a specific this value, which can be an object or any other value.

In this example, a.x works because functions in JavaScript are also objects and can have properties added to them. So, a.x adds a property x to the function a.