I have this code
var a = function(){}
var b = a.call
b() // TypeError: b is not a function
typeof b
is 'function'
and console.log(b)
shows ƒ call() { [native code] }
.
Can someone please explain this behaviour?
I have this code
var a = function(){}
var b = a.call
b() // TypeError: b is not a function
typeof b
is 'function'
and console.log(b)
shows ƒ call() { [native code] }
.
Can someone please explain this behaviour?
The reason it doesn't work is that .call()
requires a function to be the this
value when invoked, but you've detached it from a
, so there's no more relationship there.
So because b
, which is Function.prototype.call
, has been given no function for a this
arg, it has no valid function to invoke, so it gives an error.
If you did this, it'll work:
var b = a.call.bind(a);
That's because now the a
function is bound as the this
value of .call()
.
Another way would be to use .call
to invoke .call
.
var b = a.call;
b.call(a);
Now you're setting the a
function to the this
value of b
(which again is the Function.prototype.call
method), but you're doing it at the point of invocation.