Javascript调用函数 [英] Javascript call function
问题描述
call()
函数,我无法理解。 我有以下代码:
函数hi(){
console.log(hi);
}
var bye = function(param,param2){
console.log(param);
console.log(param2);
console.log(bye);
$ / code>
如果我调用 bye.call(hi() ,1,2)
,我得到 hi 1 2 undefined
如果我调用 bye.cal(1,2)
,我得到 2 undefined bye undefined
我知道 call()
函数的第一个参数必须是一个函数,接着是参数my 再见
函数接受。但是最后一个未定义的来自哪里?
第一个参数不一定是函数。第一个参数是this变量在函数调用的上下文中设置的对象。
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);
控制台应显示:1,2,bye和1。
undefined是你的函数的返回值。
在你的第一个调用中:
bye.call(hi(),1,2)
你打电话给hi()(所以它打印'hi'),不使用返回值,1和2是再见参数
在第二次电话中:
bye.cal(1,2)
1分配给此。 2是param,param2是未定义的。
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.
这篇关于Javascript调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!