JavaScript anonymous functions and closures

Source: Internet
Author: User
Tags closure

//1 definition and use of anonymous functions//1.1 Assigning an anonymous function to a variable is performed by a variablevarbox =function() {    return"Lee";} Box (); //"Lee"//1.2 Performing anonymous functions by self-executing//( anonymous function) ();(function() {    return"Lee";}) (); //"Lee"//1.3 anonymous function self-reference(function(age) {returnAge ;}) (100);// -//2 Closures//2.1 Packet Closure functionfunctionbox () {return function() {        return10; }}box (); //See below/*function () {return;}*/box () ();//Ten//2.2 Returning local variables via closuresfunctionbox () {varAge = 100; return function() {        returnAge ; };} Box (); //See below/*function () {return age;}*/box () ();// -//2.3 Using anonymous functions to implement local variables residing in memory to accumulatefunctionbox () {varAge = 100; return function() { age++; returnAge ; }}varb =box (); B ();//101b ();//102b ();//103//destroying references waiting for the garbage collector to clean upb =NULL;//2.4 About closures the This object//window is the largest global object in JS .//this is different in different scopes but points to the object itself//This refers to the window object This;//Window {...} This. Name = "Window";varbox ={name:"Box", GetName:function() {        return function() {            //inside the closure function this refers to the Window object            return  This. Name; }}}box.getname () (); //"Window"//Object ImpersonationBox.getname (). Call (Box)//"box"varbox ={name:"Box", GetName:function() {        //outside the closure function this refers to the box object        varthat = This; return function() {            returnThat.name; }}}box.getname () (); //"box"

JavaScript anonymous functions and closures

Related Article

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.