Function
Function ในภาษา Javascript ไม่ได้แตกต่างจากภาษาอื่นมากนัก เพียงแค่ไม่ต้องประกาษว่า input argument, return เป็น type อะไร
function hello() {
console.log('Hello');
}
function helloTo(name) {
console.log('Hello ' + name);
}
function formatGreeting(name) {
return 'Hello' + name;
}
hello();
helloTo('Jack');
console.log(formatGreeting(name));
ควรได้ผลลัพธ์ดังนี้
Hello
Hello Jack
Hello Jack
Function สามารถประกาศเป็นตัวแปรได้เช่นกัน
helloFrom = function(sender){
console.log('Hello from ' + sender);
};
helloFrom('Boss');
ควรได้ผลลัพธ์เป็น
Hello from Boss
เมื่อ Function สามารถใช้เป็นตัวแปรได้ ก็สามารถนำมาเป็น input ให้กับ Function ได้เช่นเดียวกัน
function formatGreeting(receiver, sender){
return 'Hello ' + receiver + ' from ' + sender;
}
function printGreeting(format, receiver, sender) {
console.log(formate(receiver, sender));
}
printGreeting(formatGreeing, 'Jack', 'Boss');
ควรได้ผลลัพธ์ดังนี้
Hello Jack from Boss
Function ไม่จำเป็นต้องสร้างไว้ก่อน สามารถสร้างขึ้นในขณะที่ต้องการได้ทันที ในภาษา Javascript เรียกว่า Anonymous function
ตัวอย่าง เช่น การใช้งาน setTimeout
setTimeout(function() {
console.log('Delayed hello');
}, 1000);
ควรได้ผลลัพธ์ดังนี้ เมื่อเวลาผ่านไป 1 วินาที
Delayed hello