Closures in JavaScript are

 

See an example:

var foo = ( function() {
        var secret = 'secret';
        // The function inside the "closure" can access the secret variable, but the secret variable is hidden from the outside
        return {
            get_secret: function () {
                // Access the secret through the defined interface
                return secret;
            },
            new_secret: function (new_secret) {
                // Modify the secret through the defined interface
                secret = new_secret;
            }
        };
    }());
    foo.get_secret (); // get 'secret'
    foo.secret; // Type error, access not allowed
    foo.new_secret ('a new secret'); // Through the function interface, we access and modify the secret variable
    foo.get_secret (); // get 'a new secret'

1. A closure means that in JavaScript, an inner function can always access the parameters and variables declared in the outer function where it is located, even after the outer function is returned (end of life). (That is, the closure breaks the "chain scope" structure rule, and the internal variables can still be accessed externally through the interface)

 

Note: You can also refer to Ranyifeng's closure introduction   http://www.ruanyifeng.com/blog/2009/08/learning_javascript_closures.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324889421&siteId=291194637