JavaScript: Send function as a parameter to another function (callbacks) JavaScript: שלח פונקציה כפרמטר לפונקציה אחרת (callbacks)
Posted on 29. פורסם ב 29. Jul, 2009 by Dragos in Coding , JavaScript & Ajax יולי, 2009 על ידי Dragos ב וקידוד, JavaScript & אייאקס
I'm sure you've seen a lot of code where functions are send as parameters, usually working as function callbacks eg: אני בטוח שראית הרבה קוד שבו הם שולחים פונקציות כפרמטרים, בדרך כלל עובד כמו callbacks פונקציה לדוגמה:
setTimeout(function () { alert('test'); },1000); setTimeout (function () (alert ( 'test');), 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. הפונקציה שלנו תנתח את פרמטר בוליאני ובמקרה ערך נכון, העביר את הפונקציה כפרמטר יבוצע.
function simpleFunc(bool,func) { פונקציה simpleFunc (BOOL, func) ( if(bool) func(); אם (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. וזה סוד te כולו.
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 (שווא, function () (alert ( 'Yupee!');) / / זה לא יתריע כלום, כי פרמטר בוליאני הוא שקר //example two / / לדוגמה שני simpleFunc(true,function() { alert('Yupee!'); }); // this will alert Yupee! simpleFunc (נכון, הפונקציה () (alert ( '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 ממסד נתונים SMF בפורום












































