JavaScript closures and callback explanations

Source: Internet
Author: User
Tags closure

One, closed package

Closures (closure) are a difficult and unique feature of the JavaScript language, and many advanced applications rely on closures.

Closures have three properties:

1. function nesting function;

2. External parameters and variables can be referenced inside the function;

3. Parameters and variables are not recycled by the garbage collection mechanism.

Closures are functions that have access to variables in another function scope, and the most common way to create closures is to create another function within one function and access the local variables of the function through another function. The use of closures has an advantage, but also its disadvantage, is that local variables can be resident in memory, you can avoid the use of global variables. Global variables can be called in every module, which is bound to be catastrophic. Therefore, it is recommended to use a private, encapsulated local variable. After the general function is executed, the local active object is destroyed and only the global scope is saved in memory. But the case of closures is different!

Example one:

Closure is the return value of a function is another function, outside the outer can be accessed through the return function of the local variables within the outer.

1234567891011121314 function outer(){ var val = 0; return function (){  val += 1;  document.write(val + "<br />"); };}var outObj = outer();outObj();//1,执行val += 1后,val还在outObj();//2outObj = null;//val 被回收var outObj1 = outer();outObj1();//1outObj1();//2

Closures cause variables to be kept in memory at all times, and if used inappropriately increases memory consumption (if many outer () are defined in the previous example, many Val variables are saved in memory).

How JavaScript works with garbage collection:

(1), in JavaScript, if an object is no longer referenced, then the object will be recycled by GC;

(2) If two objects are referenced by each other and are no longer referenced by the 3rd, then the two objects referenced by each other are also recycled.

So what are the benefits of using closures? The benefits of using closures are:

1. Want a variable to be stationed in memory for a long time

2. Avoid contamination of global variables

3. Existence of Private members

Second, callback

callback function principle: I am leaving now, to inform you. " This is an asynchronous process, "I'm out" in the process (function execution), "You" can do anything, "to" (function Completion) "Notify You" (callback) after the process.

Example one:

1234567 functiondoSomething(callback){ callback(1,2);}functionnumberAdd(a,b){ document.write(a+b);}doSomething(numberAdd);//3

Example two:

123 functionThing(name){ this.name = name;}

Add the DoSomething method to the Thing class, where the constructor invocation pattern is used

12345678 thing.prototype.dosomething = function (callback) { &NBSP; callback ( this .name); function showname (name) { &NBSP; document.write (name); } var t = new thing ( " Zhangsan " ); t.dosomething (showname); //zhangsan

If you have an array of numbers, you want to write a sort of public method, but the sort method (from small to large or from large to small) is the person who calls the sorting methods. Implementation of the sorting method can be implemented with callbacks, of course, you can write 2 methods, one is from small to large sort, one is from large to small sorting method. Callback personally think that is the decision to the actual business development engineer, he decided how to deal with, this idea is different from our usual contact, a bit unaccustomed, but this idea in the asynchronous programming in particular can see its benefits, do not know whether I understand the correct. The following example code is a typical use of callbacks:

1234567891011121314151617181920212223242526 var arr = [25,13,33,8,23,32];Array.prototype.sort = function(callback){ var arr = this; var i = 0;//i在这里定义与在for循环的括号内(for(var i = 0; i < ...))定义是一样的 for(; i < arr.length-1; i++){  var j = i + 1;  for(; j < arr.length;j++){  if(callback(arr[i],arr[j])){   var temp = arr[i];   arr[i] = arr[j];   arr[j] = temp;  }  }  }return arr;};//a-b>0表示数组从小到大排序arr.sort(function(a,b){ return a - b > 0;});document.write(arr.join(",") + "<br />");//8,13,23,25,32,33//b-a>0表示数组从大到小排序arr.sort(function(a,b){ return b - a > 0;});document.write(arr.join(","));//33,32,25,23,13,8

JavaScript closures and callback explanations

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.