Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Immediate Functions (Hàm thực thi ngay) trong JavaScript

Immediate function (IIFE) thực thi ngay lập tức khi được định nghĩa. Để hiểu vai trò, so sánh hàm thường và immediate function:

Immediate Function

(function() {
  var str = "display";
}());
function display() {
  // Trả về undefined vì str không ở scope này
  alert(str);
}

Hàm thường

var str = "display";
function display() {
  // Trả về "display" vì str ở global scope
  alert(str);
}

Ví dụ khác

var name = 'Amit';
(function(sName) {
  alert('Student name = ' + sName);
}(name));

Ứng dụng: Tạo scope riêng, tránh ô nhiễm global, dùng trong module pattern, khởi tạo một lần.