简体   繁体   English

同时使用匿名函数和存储在变量中的函数作为回调参数JavaScript

[英]Using both anonymous functions and functions stored in variables as callback arguments JavaScript

I'm not completely clear what this is supposed to mean. 我还不太清楚这是什么意思。 I guess my question is if someone could clear this up for me. 我想我的问题是,是否有人可以帮我解决这个问题。 What I know from Callbacks so far: 到目前为止,我从回调了解到的信息是:

function Hello(Callback,a,b){
Callback(a,b);
}

function Hi(a,b){
alert("Hi " + a + b);
}

Hello(Hi,5,6);

In JavaScript, Functions are Objects just like Strings and Numbers, because of that feature you are able to pass Functions as variables into other Functions. 在JavaScript中,函数是对象,就像字符串和数字一样,由于该功能,您可以将函数作为变量传递给其他函数。

function Hello(Callback,a,b){
Callback(a,b);
}

function Hi(a,b){
alert("Hi " + a + b);
}

Hello(Hi,5,6);

In your snippet, you declare a function called Hello that takes three arguments. 在您的代码段中,您声明了一个名为Hello的函数,该函数带有三个参数。 The Hello Function will then "call Callback as a Function", actually executing the Hi function that was passed in given your last line of code. 然后,Hello函数将“作为函数调用回调”,实际上执行给定最后一行代码传入的Hi函数。

You have to be careful about using Functions like, especially with "this". 您必须小心使用like之类的功能,尤其是在使用“ this”时。 Since "this" refers to the self-containing object, "this" will actually refer to the Function in certain contexts. 由于“ this”是指自包含的对象,因此“ this”在某些情况下实际上是指Function。

However, that is not what an Anonymous Function is. 但是,这不是匿名函数。 A modified version of your example: 您的示例的修改版本:

function Hello(Callback, a, b){
   Callback(a,b);
}
Hello(function(a,b){
  alert("Hi " + a + b);
}, 5, 6);

That function that get's passed in is Anonymous, it isn't named (the JavaScript engine will give it a unique name, but it won't look pretty). 传入的函数是Anonymous,它没有命名(JavaScript引擎会为其赋予一个唯一的名称,但看起来并不漂亮)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM