Home >Web Front-end >JS Tutorial >Study notes on callback functions in js_javascript skills

Study notes on callback functions in js_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:40:391118browse

What is a callback function? Before learning, I really didn’t know how to use and function the js callback function. In this article, I will introduce the example of the callback function that I am learning to the students. Students who need to know more can refer to it for reference.

Principle of callback function:

I’m leaving now and I’ll let you know when I arrive”
This is an asynchronous process. During the process of "I go" (function execution), "you" can do anything. "Arrived" (function execution completed) "notify you" (callback) after the process

Example

1.Basic method

<script language="javascript" type="text/javascript">
function doSomething(callback) {
// … 
// Call the callback
callback('stuff', 'goes', 'here');
} 
function foo(a, b, c) {
// I'm the callback
alert(a + " " + b + " " + c);
} 
doSomething(foo); 
</script>

Or use anonymous function form

<script language="javascript" type="text/javascript">
 function dosomething(damsg, callback){
  alert(damsg);
  if(typeof callback == "function") 
  callback();
 } 
dosomething("回调函数", function(){
  alert("和 jQuery 的 callbacks 形式一样!");
 }); 
</script>


2. Advanced methods

Use the call method of javascript

<script language="javascript" type="text/javascript">
function Thing(name) {
this.name = name;
}
Thing.prototype.doSomething = function(callback) {
// Call our callback, but using our own instance as the context
callback.call(this);
}
 
function foo() {
alert(this.name);
}
 
var t = new Thing('Joe');
t.doSomething(foo); // Alerts "Joe" via `foo`
</script>


Pass parameters

<script language="javascript" type="text/javascript"> 
function Thing(name) {
this.name = name;
}
Thing.prototype.doSomething = function(callback, salutation) {
// Call our callback, but using our own instance as the context
callback.call(this, salutation);
} 
function foo(salutation) {
alert(salutation + " " + this.name);
} 
var t = new Thing('Joe');
t.doSomething(foo, 'Hi'); // Alerts "Hi Joe" via `foo`
</script>

Use javascript’s apply to pass parameters

<script language="javascript" type="text/javascript">
function Thing(name) {
this.name = name;
}
Thing.prototype.doSomething = function(callback) {
// Call our callback, but using our own instance as the context
callback.apply(this, ['Hi', 3, 2, 1]);
} 
function foo(salutation, three, two, one) {
alert(salutation + " " + this.name + " – " + three + " " + two + " " + one);
} 
var t = new Thing('Joe');
t.doSomething(foo); // Alerts "Hi Joe – 3 2 1" via `foo`
</script>

Example
//If the data source provided is an integer, which is the score of a certain student, when num32f6187ffd70460078df3ca962a514ec0, it will be processed by the high-level layer.

//Copy the following function and save it as 1.js

function f(num,callback){
 if(num<0) { 
 alert("调用低层函数处理!");
 alert("分数不能为负,输入错误!"); 
 }else if(num==0){
  alert("调用低层函数处理!");
 alert("该学生可能未参加考试!");
 }else{
 alert("调用高层函数处理!");
 callback();
 }
}

//Save the following test.html file and 1.js in the same directory:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<script src="1.js" type="text/javascript"></script>
<title>无标题文档</title>
<script type="text/javascript">
 function test(){
  var p=document.getElementById("pp");
 pp.innerText="";
  var num=document.getElementById("score").value;
 f(num,function(){ //匿名高层处理函数
 if(num<60) alert("未及格!");
 else if(num<=90) alert("该生成绩优良!");
 else alert("该生成绩优秀!"); })
 pp.innerText="by since1978 qq558064!"
 }
</script>
</head>

<body>
<p>
回调函数示例:当学生成绩score<=0分时候,由底层处理;当score>0时,由高层处理。
</p>
请输入学生成绩<input type="text" id="score"> 
<input type="button" onClick="test()" value=" 看看结果">
<p id="pp"></p>
</body>
</html>

The following are additions from other netizens:

Callback mode in javascript:

looks like:

function writeCode(callback){ 
   //执行一些事物, 
   callback(); 
   //... 
  } 
 
  function intrduceBugs(){ 
   //....引入漏洞 
  } 
 
writeCode(intrduceBugs); 

We pass the application of the function to writeCode() and let writeCode execute it at the appropriate time (called after returning)

Let’s look at a not-so-good example first (it will be reconstructed later):

//模拟查找页面中的dom节点,将查找到的节点存在数组里面统一返回 
  //此函数只用于查找不对dom节点做任何的逻辑处理 
  var findNodes = function(){ 
   var i = 100000;//大量的循环, 
   var nodes = [];//用于存储找到的dom节点 
   var found; 
   while(i){ 
    i -=1; 
    nodes.push(found); 
   } 
   return nodes; 
  } 
 
  //将查找找到的dom节点全部隐藏 
  var hide = function(nodes){ 
   var i = 0, 
    max = nodes.length; 
   for(;i<max;i++){ 
//findNodes后面有括号代表立即执行,先执行findNodes()然后执行hide()< hide(findNodes()); 执行函数 } ; 
nodes[i].style.display="none"
}

上面的方法是低效的,以为hide()必须再次遍历有findNodes()返回的数组节点,如何避免这种多余的循环呢。 
  我们不能直接在findNodes中对查询到的节点进行隐藏(这样检索就可修改逻辑耦合了),那么他就不再是一个通用函数了。 
  解决方法是用回调模式,可以将节点隐藏逻辑以回调函数方式传递给findNodes()并委托其执行

//重构findNodes以接受一个回调函数 
   var findNodes = fucntion(callback){ 
    var i = 100000, 
     nodes = [], 
     found; 
    //检查回调函数是否可用调用的 
    if(typeof callback !== 'function'){ 
     callback = false; 
    } 
    while(i){ 
     i -= 1; 
     if(callback){ 
      callback(found); 
     } 
     nodes.push(found); 
    } 
    return nodes; 
   } 
 
   //回调函数 
   var hide = function(node){ 
    node.style.display = 'none '; 
   } 
   //找到后续节点并在后续执行中对其进行隐藏 
 findNodes(hide);//先执行findNodes然后执行hide,当然回调函数也可以在调用主函数时创建:findNodes(function(node){node.style.display = 'none';});
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn