ฟังก์ชันการทำงานทันทีที่ถูกกำหนด เพื่อให้เข้าใจถึงบทบาทของฟังก์ชันทันที มาดูความแตกต่างระหว่างฟังก์ชันและฟังก์ชันทันที -
นี่คือฟังก์ชันทันที −
(function() {
var str = "display";
}());
function display() {
// this returns undefined
alert(str);
} นี่คือฟังก์ชัน −
var str = "display";
function display() {
// This returns "display"
alert(str);
} มาดูตัวอย่างการใช้งานแบบทันทีกัน −
var name = 'Amit';
(function(sName) {
alert( 'Student name = ' + sName );
}(sName))