Javascript call function

2020-07-22 10:10发布

问题:

I have been testing some code lately trying to understand javascript a little bit better. Then I came across the call() function wich I can't get to understand well.

I have the following code:

function hi(){
    console.log("hi");
}

var bye = function(param, param2){
    console.log(param);
    console.log(param2);
    console.log("bye");
}

If I call bye.call(hi(), 1, 2), I get hi 1 2 undefined

And if I call bye.cal(1,2), I get 2 undefined bye undefined

for which I understand the call() function first parameter has to be a function, followed by the amount of parameter my bye function accepts. But where is the last undefined coming from?

回答1:

This first parameter doesn't have to be a function. The first parameter is the object to which the "this" variable is set to in the context of the function call.

var bye = function(param, param2){
    console.log(param);
    console.log(param2);
    console.log("bye");
    console.log(this.x)
}

t = {'x': 1};

bye.call(t, 1, 2);

And the console should show: 1, 2, "bye" and 1.

The undefined is the return value of your function.

In your first call:

bye.call(hi(), 1, 2)

You're calling hi() (so it prints 'hi'), the return value is not used, and 1 and 2 are the parameters to bye.

In your second call:

bye.cal(1,2)

1 is assigned to this. 2 is param, and param2 is undefined.



回答2:

You are getting the undefined because you function does not return anything, it only prints output to the screen. So, your code could be like this:

var obj = {foo: "hi"};
var bye = function(param, param2){
    console.log(this.foo);
    console.log(param);
    console.log(param2);
}

bye.call(obj, 1, 2)   // "hi", 1, 2

You can read here at MDN for more info on .call().



回答3:

fn.call() allows you to set the value that this will have when the function is called. That value of this must be the first argument to fn.call().