简体   繁体   中英

turn object into JSON string and null it

I am still learning how referencing and garbage collector work in javascript, therefore in my attend to cut down bloats and leaks. I create a factory that holds an object, which values can be pass to it or get from it.

.factory('lib', function(){
   var lib={};
   return {
     set: function(id,value,isObj){
       if(isObj){
         lib[id]=JSON.stringify(value);
       }else{
         lib[id]=value;
       }
     },
     del: function(id){
       lib[id]=null;
     }
   };
})

.controller('testCtrl',function(lib,$timeout){
  lib.set("1",{'name':'James','sureName':'Potter'},true);
  $timeout(function(){
    lib.del("1");
  },1000);
})

So my questions are; by turning my obj to string, later turned string and now as a null value. Will my original obj be reachable and will it get collected by the garbage collector? Also what happen to the properties of the obj I try to turn into string?

Since the object is created from an object literal in the function argument list, there are no references to the object outside the set() function. The only reference is the local variable value , and when the set() function returns that variable goes away, so the object can be garbage collected. So can all its properties, since they also contain literals, not values that other variables have references to.

You didn't "turn the object into a string", you simply created a new string that contains a representation of the object. The string and the object are completely independent.

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