2

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
2
  • 1
    The questions are in the inline comments in his code. Commented Sep 19, 2011 at 16:46
  • I think you are asking about what's discussed here - stackoverflow.com/questions/7459769/… Commented Sep 19, 2011 at 16:47

1 Answer 1

7
Function.call.apply(Foo.prototype.method, arguments);

is the same as

Foo.prototype.method.call(arguments[0], arguments[1], arguments[2], ...);

which, in your case, is the same as:

Foo.prototype.method.call(1, 2, 3);

This means, inside Foo.prototype.method, this will refer to 1, but as this always has to reference an object (in non-strict environment), 1 is converted to a Number object.

The last value is undefined because you are effectively only passing 2 and 3 (two arguments) to the method (instead of three).

So in the end, the code is doing something similar to this:

var obj = new Number(1);
obj.method = Foo.prototype.method;
obj.method(2,3);
Sign up to request clarification or add additional context in comments.

1 Comment

Note that on strict mode, this is no longer implicitly converted to number, e.g.: (function () {'use strict'; return typeof this; }).call(1) == 'number'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.