JavaScript: Send function as a parameter to another function (callbacks) JavaScript的:寄另一个函数(回调参数功能)
Posted on 29.发布29。 Jul, 2009 by Dragos in Coding , JavaScript & Ajax 2008年7月,2009年在编码 ,JavaScript的与阿贾克斯 德拉戈什
I'm sure you've seen a lot of code where functions are send as parameters, usually working as function callbacks eg:我相信你已经看到了大量的代码,其职能是作为参数传送,通常作为回调函数的工作,例如:
setTimeout(function () { alert('test'); },1000); setTimeout(函数()(警报('测试');),1000);
But how does the function setTimeout execute the passed function as a parameter?但如何执行该函数setTimeout作为参数传递的功能? The answer is simple, but I need to provide you an example to understand it答案很简单,但我需要你提供一个例子来理解 ![]()
Let's create a simple function, accepting two parameters: first a boolean value, the second – a function.让我们创建一个简单的函数,接受两个参数:一个布尔值第一,第二-一个函数。 Our function will analyze the boolean parameter and in case the value is true , the function passed as a parameter will be executed.我们的功能将分析布尔参数,如果该值为 true,作为参数传递函数将被执行。
function simpleFunc(bool,func) {功能simpleFunc(布尔,函数)( if(bool) func();如果(布尔)函数(); } )
As you notice, we add parentheses after the name of the second parameter, because we'll treat it as a function.你可能注意到了,我们添加后的第二个参数的名称括号,因为我们会当成一个函数。 And that's te whole secret.这就是德的全部秘密。
Now that is how we will use the simpleFunc function:现在是我们将如何使用simpleFunc功能:
simpleFunc(false,function() { alert('Yupee!'); }; // this won't alert anything, because the boolean parameter is false simpleFunc(假,函数()(警报('Yupee!');)/ /这不会警告任何事情,因为布尔参数为false //example two / /例子2 simpleFunc(true,function() { alert('Yupee!'); }); // this will alert Yupee! simpleFunc(真,函数()(警报('Yupee');)); / /这将提醒Yupee!![]()
Wish you luck!祝您好运!
Related posts:相关岗位:
- Javascript: How to validate email address with JavaScript? JavaScript的:如何用JavaScript验证电子邮件地址?
- JavaScript: How to get the index (position within a group) of an object with jQuery? JavaScript的:如何获取指数(位置在一组与jQuery对象)?
- JavaScript: What if jQuery animation doesn't fire/start? JavaScript的:如果jQuery的动画不火/开始?
- Coding: How to get code suggestions and function completion in Netbeans? 编码:如何获取代码和功能的建议在Netbeans完成?
- Coding:How to fetch user profile data with SSI.php from a SMF forum database 编码:如何获取从证券保证金融资论坛数据库SSI.php用户配置文件数据












































