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

Cách bảo toàn biến trong hàm closure JavaScript

Để bảo toàn biến trong closure function, đừng gán lại thành object rỗng mỗi lần gọi. Code sau sai vì reset webLinks mỗi lần:

webLinks = {};

Sửa lại để giữ giá trị:

var webLink = function (containerId) {
  var link1 = "https://www.qries.com",
      link2 = "https://www.tutorialspoint.com";
  var webLinks = {}; // Chỉ khởi tạo 1 lần khi tạo closure
  return function(Id) {
    webLinks[id] = "My " + id;
    document.write(webLinks);
  };
}();

Giải thích: Biến webLinks nằm trong scope của IIFE bao ngoài. Hàm nội bộ (closure) tham chiếu đến nó, nên giá trị được giữ qua các lần gọi.