Js interview questions

    var i = 100;

    function addI(){
        var i = 0;
        return function(){
            iPP;
            console.log(i);
        }
    }

    addI()();       // 1
    addI()();       // 1
    var c = addI();
    c();            // 1
    c();            // 2

encountered this interview question today, ask for the popularization of science.
Why is the addI () () all 1 (understandably), while the c () () execution I is incremented?

May.14,2021

is a bit shameful and unsure-- I understand that: add () () simply executes the add method, and when the add method is referenced to the c object, the c object always exists (lively referencing the method in the), add method forms a closure (at this time the add method referenced by the c object has formed a closure). On the first call, the I object in the add method is assigned a value of 0, and when the anonymous function is executed, the internal I has no value, find the external I, and PP. On the second call, the add method declares an I object again, but the I in the internal anonymous function at this time retains the value of the last call. So directly in the result of the last call iPP. I don't know whether it is correct


addI () = addI () / / false

each run produces a different result function, each referring to the I value in its own closure.
if the same function runs, it will continue to modify the I value in the closure to which the function belongs.

Menu