官术网_书友最值得收藏!

Anonymous functions and callbacks

Often, you will need to use a temporary function that you don't necessarily want to declare ahead of time. In this type of scenario, you can use an anonymous function, which is simply a function that is declared at the time you need it. This is similar to the function expression context we explored earlier, with a simple difference that the function isn't assigned to a variable so it has no way of being referenced to later. The most common use of anonymous functions is when they are defined as a parameter to another function (most notably when used as a callback).

One of the most common places to use an anonymous function (which also acts as a callback even if you didn't realize it) is with setTimeout or setInterval. These are two standard JavaScript functions that will execute code after a specified delay (in milliseconds) or repeat the execution of code after a specified delay. Here is an example of one of them, setTimeout, using an anonymous inline function:

console.log('Hello...'); 
setTimeout(function() { 
  console.log('World!'); 
}, 5000); 
// => Hello... 
// (5000 milliseconds i.e. 5 second delay) 
// => World! 

You can see that the anonymous function was passed as the first parameter to setTimeout because setTimeout expects a function. You can, if you desire, declare the function ahead of time as a variable and pass that to setTimeout instead of the inline anonymous function:

var sayWorld = function() { 
  console.log('World!'); 
} 
setTimeout(sayWorld, 5000); 
// (5 second delay) 
// => World! 

The anonymous function just acts as a clean inline disposable function.

Callbacks are important because one of the most powerful (and confusing) features of JavaScript is that it's asynchronous. This means that every line executes sequentially, but it doesn't wait around for code that might be taking longer than it should (even if by design). We have explored this via an example in the first chapter while looking into the asynchronous nature of Node.js.

Mozilla has a detailed tutorial on JavaScript concepts, which we advise you to go through once you finish this chapter. The tutorial includes highly advanced concepts, such as closures, that were not covered in this chapter due to the depth of the topic. So refer to this Mozilla Development Network article at https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript.
主站蜘蛛池模板: 高要市| 汝城县| 昌图县| 固阳县| 土默特左旗| 奉化市| 池州市| 翁牛特旗| 昔阳县| 巧家县| 浏阳市| 牡丹江市| 嘉峪关市| 鄂伦春自治旗| 方正县| 石嘴山市| 正镶白旗| 杭州市| 宁阳县| 武川县| 莱西市| 乌什县| 濮阳县| 黔东| 延津县| 阿坝县| 平利县| 禹州市| 河东区| 宣恩县| 休宁县| 梅河口市| 随州市| 陈巴尔虎旗| 新余市| 延川县| 涿鹿县| 武安市| 旺苍县| 上饶县| 凉山|