JavaScript functions (three)--closures and scopes

Source: Internet
Author: User

Closure concept

Only a child function inside a function can read a local variable, so a closure can be understood as "a function defined inside a function". In essence, closures are bridges that connect functions inside and outside of functions

Example

function outer(){    var localVal = 30;    return localVal;}outer();//30function outer(){    var localVal = 30;    return function() {        return localVal;    }}var func = outer();func();//30

Function: For example, to nest a function in a function, a closure allows the nested function to access the local variables of the function that wraps it.

Packaging
(function(){    var _userId = 123;    var _typeId = ‘item‘;    var export = {};        function converter(userId){        return + userId;    }        export.getUserId = function(){        return converter(_userId);    }        export.getTypeId = function(){        return _typeId;    }    window.export = export;})();export.getUserId();//123export.getTypeId();//itemexport._uerId;//undefinedexport._typeId;//undefinedexport.converter;//undefined
Closure traps
var tasks = [];for (var i=0; i<3; i++) {    tasks.push(function() {        console.log(‘>>> ‘ + i);    });}console.log(‘end for.‘);for (var j=0; j<tasks.length; j++) {    tasks[j]();}

The output is 3. The reason for this problem is that the function is not executed at the time it was created, so we print end for. Before executing the function, because the function references the loop variable i, and I is scoped to the entire function, not the loop, and when the function executes, the value of I becomes 3.

Workaround
Then create a function that passes the loop variable as a function parameter:

var tasks = [];for (var i=0; i<3; i++) {    var fn = function(n) {        tasks.push(function() {            console.log(‘>>> ‘ + n);        });    };    fn(i);}//简化语法,直接用匿名函数的立即执行模式(function() { ... })()var tasks = [];for (var i=0; i<3; i++) {    (function(n) {       tasks.push(function() {           console.log(‘>>> ‘ + n);        });    })(i);}
Summarize

Advantages: Flexible and convenient, package
Cons: Wasted space, memory leaks, performance consumption

JavaScript functions (three)--closures and scopes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.