I want to understand the following behaviour because the explanation on this site javascript garden is not enough for me.
It would be much appreciated if you could give me a clear explanation about
the questions which are in the inline comments.
Here the example:
function Foo() {}
Foo.prototype.method = function(a, b, c) {
console.log(this, a, b, c);
};
Foo.method = function() {
Function.call.apply(Foo.prototype.method, arguments);
};
Foo.prototype.method(1,2,3) // Foo { method=function()} 1 2 3 //this output is obvious
Foo.method(1,2,3) // Number {} 2 3 undefined // I want understand why the first argument is a number and the last one is undefined
is the same as
which, in your case, is the same as:
This means, inside
Foo.prototype.method,thiswill refer to1, but asthisalways has to reference an object (in non-strict environment),1is converted to aNumberobject.The last value is
undefinedbecause you are effectively only passing2and3(two arguments) to the method (instead of three).So in the end, the code is doing something similar to this: