JavaScript: Send function as a parameter to another function (callbacks) JavaScript: ส่งหน้าที่เป็นพารามิเตอร์ทำงาน (callbacks อื่น)
Posted on 29. โพสต์ใน 29. Jul, 2009 by Dragos in Coding , JavaScript & Ajax ก.ค., 2,009 โดย Dragos ใน การเข้ารหัส, JavaScript และ Ajax
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 (ฟังก์ชัน () (แจ้งทดสอบ ( '');) 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 (เท็จหน้าที่ () (แจ้ง Yupee ( '!)); / / นี้จะไม่เตือนอะไรเพราะพารามิเตอร์แบบบูลเป็นเท็จ //example two / / ตัวอย่างสอง 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 จากฐานข้อมูลเวที SMF












































