Home  >  Q&A  >  body text

javascript - Usually everyone uses functions for closures. What if I use objects or closures?

let a = [];
function test1(){
    let ta = Math.random();
    let tb = "test2";
    let obj1 = {
        t1: ta
    }
    a.push(obj1);
}

test1();
        

Will function test1 release memory after calling it like this?
Global variable a puts a reference to an object, which is in function test1. Why do I think test1 will not release the memory? Please give me some advice. . . .

PHP中文网PHP中文网2710 days ago643

reply all(3)I'll reply

  • 淡淡烟草味

    淡淡烟草味2017-05-19 10:44:53

    a and test1 share a running context, that is, a and test1 coexist and die~
    I don’t know if my understanding is wrong~For example:

    function test() {
        let a = [];
        function test1(){
            let ta = Math.random();
            let tb = "test2";
            let obj1 = {
                t1: ta
            }
            a.push(obj1);
        }
        test1();
    }
    test();

    After executing test, I think test1 will be released, and a will also be released.
    If it is not in a function but directly under the window, test1 will always exist~

    reply
    0
  • 滿天的星座

    滿天的星座2017-05-19 10:44:53

    I misunderstood before, this should be two problems.

    After execution, the variables of test1 are not directly referenced, so the execution environment of test1, that is, the context, should be recycled. This is not a closure. In addition, the function body of test1 itself is an attribute that belongs to the context in which it is located. As long as the context is still there, the function body itself will not be recycled.

    reply
    0
  • 淡淡烟草味

    淡淡烟草味2017-05-19 10:44:53

    Let’s talk about the conclusion first, isn’t it
    First of all, the definition of closure is a function that can access free variables, which is inconsistent with the definition

    If your understanding is wrong
    Please change your example

    let a = [];
    function test1(){
        let ta = Math.random();
        let tb = "test2";
        let obj1 = {
            t1: ta
        }
        return obj1;
    }
    a.push(test1())
    The object pointed to by

    original obj1 also exists in a, but do you think this is still a closure?

    In your example, after test1 is executed, ta, tb, and obj1 are all released.
    The object pointed to by the obj1 variable created in it is added to the global variable a. After test1 is executed, a[0] Points to this object. Since this object is referenced by a[0], it will not be released, but it has nothing to do with obj1. The scope of obj1 has not changed during the whole process. What is pushed in a is pointed to by obj1. object instead of obj1

    I don’t know if you can understand this. My Chinese skills are too poor and I feel like I can’t speak clearly = =

    reply
    0
  • Cancelreply