简体   繁体   中英

How to prevent and guard against closure memory leaks

var utils = (function() {
  var playlistutils = (function() { // playlist utils
    return {
      saveplaylisobj: function(playlist) {
        if (playlist) {
          localStorage.setItem('playlistobj', JSON.stringify(playlist));
        }
      },
      getplaylistobj: function() {
        var plobj = localStorage.getItem('playlistobj');
        if (plobj) {
          return JSON.parse(plobj) || {};
        }
      }
    };
  })();


  return {
    playlistutils: playlistutils
  };
})();

Could this closure possibly be causing a memory leak ?

I'm running into an issue where chrome mobile for android crashes intermittently when running my web application.

Reference: What does this stack trace mean?

App specifics : Server : JBOSS Frameworks : Angular heavy, javascript and jQuery

I don't see a leak here. And, regardless for a leak to be material it has to either hold a large amount of memory or be something that is created and leaked thousands of times or some combination of the two. This doesn't look like something that would be declared more than once and does not hold large amounts of memory.

In any case, your use of IIFEs here is an overcomplication (leading to hard to follow code) and is entirely unnecessary. You can instead just use an object literal which has no opportunity for a closure:

var utils = {
    playlistutils: {
        saveplaylistobj: function(playlist) {
            if (playlist) {
              localStorage.setItem('playlistobj', JSON.stringify(playlist));
            }
        },
        getplaylistobj: function() {
            var plobj = localStorage.getItem('playlistobj');
            if (plobj) {
              return JSON.parse(plobj) || {};
            }
        }
    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM