Site front-end _javascript-basic primer. 0016.JavaScript Anonymous Closures

Source: Internet
Author: User

Anonymous functions:

Description: An anonymous function is a function that has no name, and a closure is a function that accesses variables in a function scope.

normal function UserInfo (name) {return Name}alert (userInfo (' Li Full '))//anonymous function var userInfo = function (name) {return name}    Alert (UserInfo)//self-invocation (function (name) {alert (name)}) (' Li full ')//Closure function UserInfo (name) {var userName = name return function () {alert (userName)}}userinfo (' Li Full ') ()


Deep closures:

Description: A closure is a function that has access to a variable in another function scope, and a common way to create closures is to create another function inside one function and access the local variables of the function through another function

Features: Closures can place local variables in memory, avoid using global variables (global variables can be polluted by the use of variables inside functions), and use closures to achieve global variable effects but local variable functions can be isolated from the external environment

Cumulative effect-Global implementation var count = 1function Add () {This.count + = 1}add () alert (count)//cumulative effect-closure implementation function Add () {var count = 1 return function () {count + = 1 return count}}res = Add () alert (res ()) alert (res ())

Note: Because the local variable returned by the scope in the closure is not immediately reclaimed, it may consume more memory, and excessive use can result in degraded performance, so use closures when it is necessary, or set to a null tag when it is finished


Closure this:

Note: In the absence of any running environment, closures are usually directed to the window because they do not belong to any object's properties and methods, but we can also bind the runtime by impersonating the object, changing the point, or bind.

Var userinfo = {    sayenv: function () {         return function () {             alert (This)         }    }}//  This time in the closure of this point to Windowuserinfo.sayenv () ()//  impersonating the object, let the closure this point to userinfouserinfo.sayenv (). Call (UserInfo)//  To borrow this, let the closure this point userinfovar userinfo = {    sayenv: function () {         var _this = this         return function () {             Alert (_this)         }    }}userinfo.sayenv ()//   Use bind to make the closure this point userinfovar userinfo = {    sayenv: function () {          return function () {             Alert (This)         }.bind (this)     }} Userinfo.sayenv () ()


Memory leaks:

Note: Although multiple browsers handle different garbage collection mechanisms, a memory leak is often caused by a closure loop referencing an object or variable, resulting in a long-term memory resident, It is strongly recommended that you assign a value to a variable at the time of the circular reference and then set the loop reference variable to null tag deletion to avoid a memory leak


Block scope:

Description: JS does not have block-level scope of the characteristics, so the block range of the variable I can also be accessed outside the block, at this time can be modeled by the block-level scope to avoid this problem

for (var I=1; I<=math.floor (Math.random () * (10+1)), i++) {}//I out of block range should be destroyed, but not destroyed, and can be accessed console.log (i)/* * Impersonate a block-level scope (private scope) to destroy the variable out of scope (function () {for var i=1; I<=math.floor (Math.random () * (10+1)); i++) {}}) () Console.log (i)

Description: After a block-level scope (private scope), any variables defined in the anonymous function are destroyed at the end of execution, so using this method can reduce the memory problems that are used by closures, because there is no reference to the anonymous function, and as long as the function is executed, it can immediately destroy its scope chain.


Private variables:

Note: variables defined in any function can be considered as private variables because they cannot be accessed externally, so the effect of private variables can be achieved by defining the constructor to publicly access these private properties

function User () {//constructor private variable var name= ' Li full '//private variable external access interface This.getname = function () {return name} Private variable External setting interface This.setname = function (value) {name = value}}limanman = new User () Console.log (limanman.ge Tname ()) limanman.setname (' Liu Jianjin ') Console.log (Limanman.getname ())

Problem: Using a constructor to declare a private variable with an external access setting interface to implement encapsulation causes all instances to create the interface object once and all instances have the same access settings interface, which allows us to automate the optimization of the inheritance through the prototype object.

Put at the block level scope (function () {var name = '//skillfully use global constructor User = function (value) {name = value}//Set prototype object's obtained Fetch interface User.prototype.getName = function () {return name}//Set the prototype object's settings interface User.prototype.setName = function (value) {name = value}}) ()//Instantiate global constructor Userlimanman = new User (' Li full ') Console.log (Limanman.getname ()) limanman.setname (' Liu Jianjin ') Console.log ( Limanman.getname ())

Description: The prototype Mode + block scope method is used to implement the access settings interface shared between multiple instances, without having to recreate each instantiation, and the contents of the block scope are externally isolated.


Module mode:

Description: All of the above are constructors that create private variables and privileged methods, and object literals are often created using module mode

function User (value) {name = value return {getname:function () {return name}, Setname:function (value) {name = value}}}limanman = User (' Li full ') Console.log (limanman.get Name ()) limanman.setname (' Liu Jianjin ') Console.log (Limanman.getname ())



This article is from the "ζ Automated operation and maintenance development Road ζ" blog, please be sure to keep this source http://xmdevops.blog.51cto.com/11144840/1853403

Site front-end _javascript-basic primer. 0016.JavaScript Anonymous 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.