Javascript call function

心已入冬 提交于 2019-12-04 14:38:23

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.

Zero Fiber

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().

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!