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?
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.
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().
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().
来源:https://stackoverflow.com/questions/17017115/javascript-call-function