简体   繁体   English

将对象转换为JSON字符串并将其null

[英]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. 我仍在学习如何在javascript中使用引用和垃圾收集器工作,因此在我的工作中减少了膨胀和泄漏。 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. 通过将我的obj转换为字符串,后来转换为字符串,现在作为空值。 Will my original obj be reachable and will it get collected by the garbage collector? 我的原始obj是否可以访问并被垃圾收集器收集? Also what happen to the properties of the obj I try to turn into string? obj的属性发生了什么,我试图变成字符串?

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. 由于对象是从函数参数列表中的对象文字创建的,因此没有对set()函数之外的对象的引用。 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. 唯一的引用是局部变量value ,当set()函数返回该变量时,该对象可以被垃圾收集。 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. 字符串和对象完全独立。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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