How to preserve variables in a JavaScript closure function?

JavascriptWeb DevelopmentFront End Technology

To preserve variables in a JavaScript closure function, do not set it to empty. Right now, the following is set to empty object each time it is called 

webLinks = {};

Use the following code to retain the value:

var webLink = function (containerId) {
   var link1 = "http://www.qries.com",
   link2 = “http://www.tutorialspoint.com”;
   var webLinks = {};
   return function(Id) {
      webLinks [id] = "My " + id;
      document.write(webLinks);
   }
})();
raja
Published on 24-Jan-2018 06:59:42
Advertisements