For learning purpose, I wrote a piece of (meaningless) code like this:
Function.prototype.invoke = function(...args) {
return this(...args);
}
const foo = (a, b) => a + b;
console.log(foo.invoke(1, 2)); // 3, all right!
const arr = [];
arr.push.invoke(1,2); // TypeError: Cannot convert undefined or null to object
console.log(arr);
Here I define a method on Function's prototype named invoke, which is used to just invoke a function by foo.invoke(args)(instead of the conventional way foo(args)). I wonder why foo runs while arr.push can't.
As far as I know, this result from the this problem. this in my invoke method is push, but this's this(push's caller) is window, which is not a array-like object(?). But why the error is Cannot convert undefined or null to object?
What on earth is the reason for this error? Is there any way to correct it?
push'sthisiswindow" - no, it's not. That's a myth that comes from sloppy-mode functions. Thethisargument isundefinedwhen you don't pass a receiver. Try yourself with(function() { "use strict"; console.log("this value:", this); }).invoke()window, from "has alengthproperty" perspective, can be regarded as an array-like object, but still it can't be called using push, though it is another story. Thank you~!