开发者

Passing Arguments in javascript

开发者 https://www.devze.com 2023-04-06 02:43 出处:网络
I want to understand 开发者_开发问答the following behaviour because the explanation on this sitejavascript garden is not enough for me.

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


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号