Deep into JavaScript -- Closures

Keywords: Javascript JQuery Attribute

concept

Closure refers to the phenomenon that a local variable in a function can not be destroyed after it is invoked by another function. Functions are the only structure in JavaScript that has its own scope, so the creation of closures depends on functions.

 var Foo = function() {
     var name = 'staven';
     this.getName = function() {
         return name;
     };
 };
 var foo = new Foo();
 console.log(foo.name);             //undefined
 console.log(foo.getName());     //staven

Loops in closures

This configuration mechanism of_scope chain leads to a noteworthy side effect that closures can only obtain the last value of any variable in a function.

for(var i = 0; i < 10; i++) {
    setTimeout(function() {
        console.log(i);  //10 outputs
    }, 1000);
}

In order to get the cyclic serial number correctly, it is better to use self-executing anonymous functions.

for(var i = 0; i < 10; i++) {
    (function(e) {
        setTimeout(function() {
            console.log(e);  
        }, 1000);
    })(i);
}

this in closures

_The execution environment of anonymous functions is global, so its this object usually points to window (when the execution environment of functions is changed by call() or apply(), this will point to other objects).

var name = 'Overall situation';
var obj = {
    name: 'local',
    getName: function(){
        var that = this;
        return function(){
            return that.name;
        }
    }
};
console.log(obj.getName()());   //local

_Keep this object in an external scope in a variable accessible by a closure, so that it can be accessed by a closure.

var name = "Overall situation";
var obj = {
    name: "local",
    getName: function() {
        var that = this;
        return function() {
            return that.name;
        };
    }
};
console.log(obj.getName()());  //"Partial"

The role of closures

Simulated block-level scope:

_Block-level scopes (private scopes) can be used as long as we need some variables temporarily. When an anonymous function is executed, its domain chain is destroyed immediately, thus reducing the resource occupancy of closures.

(function($, window, document, undefined){
    var name = "staven";
    $.fn.getName = function(){
        
    };
})(jQuery, window, document);
Keep variables in memory:

_Cache Data and Curitization

Simulate private attributes and private methods:
//Implementing with Closure
var Book = (function(){
    //Static private variables
    var bookNum = 0;
    //Static Private Method
    function checkBook(name){
        console.log("checking Book……");
    }
    //Create class
    function _book(newId, newName, newPrice){
        if(this instanceof _book){
            //private variable
            var name, price;
            //Private method
            function checkID(id){
                console.log("checking id……");
            }
            //privileged method
            this.getName = function(){};
            this.getPrice = function(){};
            this.setName = function(){};
            this.setPrice = function(){};
            //Public attribute
            this.id = newId;
            //public Method
            this.copy = function() {
                console.log("copying……")
            };
            bookNum++;
            if(bookNum > 100){
                throw new Error('We only publish 100 books.');
            }
            //constructor
            this.setName(name);
            this.setPrice(price);
        }else{
            return new _book(newId, newName, newPrice);
        }
        
    }
    //Building prototypes
    _book.prototype = {
        //Static Common Attributes
        isJSBook:false,
        //Static Common Method
        show:function(){
            console.log("showing……");
        }
    };
    //Return class
    return _book;
})();
Book(21,'staven',23).show();        //showing……
Book(21,'staven',23).copy();        //copy……
var book = new Book(21,'staven',23);
book.show();    //showing……
book.copy();    //copying…… 

Because closures carry the scope of functions that contain them, they take up more memory than other functions. Overuse of closures can lead to overuse of memory. It is recommended that closures be considered only when absolutely necessary.

Posted by jscix on Sat, 13 Apr 2019 14:45:33 -0700