Node.js后端开发 - 基础篇 #3 回调函数

355 阅读2分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。 ​

文章目录

一、函数和函数表达式

二、回调函数

1、回调函数,写法一

2、回调函数,写法二

3、回调函数,写法三


上一篇文章我们介绍了nodejs的全局对象 Node.js后端开发 - 基础篇 #2 全局对象,这篇文章我们继续介绍nodejs相关知识点——nodejs的回调函数。废话不多说,下面我们来看看函数是怎样的?

一、函数和函数表达式

代码示例:

//定义函数
function sayHello() {
    console.log("hello");
}

//调用函数
sayHello();

我们来看一下输出结果:

bogon:hello-nodejs luminal$ node app
hello
bogon:hello-nodejs luminal$ 

很简单就不多说了,下面我们来看看函数表达式是怎么样的呢?

代码示例:

//定义函数表达式
var sayBye = function(){
    console.log("Bye");
}
//调用函数表达式
sayBye();

我们来看一下输出结果:

bogon:hello-nodejs luminal$ node app
Bye
bogon:hello-nodejs luminal$ 

根据输出结果,我们知道这两种方式效果一样、差不多,我们以后都可以使用!下面我们来看看回调函数,以后在写nodejs项目的时候会经常用到。

二、回调函数

1、回调函数,写法一

我们先从基础介绍,代码示例:

//定义回调函数
function callFunction(fun) {
    fun();
}

//定义函数表达式
var sayBye = function(){
    console.log("Bye");
}

//调用回调函数
callFunction(sayBye);

我们来看一下输出结果:

bogon:hello-nodejs luminal$ node app
Bye
bogon:hello-nodejs luminal$ 

2、回调函数,写法二

下面我们来看看加一个参数的效果,代码如下:

//定义回调函数
function callFunction(fun,name) {
    fun(name);
}

//定义函数表达式
var sayBye = function(name){
    console.log(name + "Bye");
}

//调用回调函数
callFunction(sayBye,"yyh");

我们来看一下输出结果:

bogon:hello-nodejs luminal$ node app
yyhBye
bogon:hello-nodejs luminal$ 

3、回调函数,写法三

代码示例:

//定义回调函数
function callFunction(fun,name) {
    fun(name);
}

//调用回调函数
callFunction(function (name) {
    console.log(name + "Bye");
},"yyh");

我们来看一下输出结果:

bogon:hello-nodejs luminal$ node app
yyhBye
bogon:hello-nodejs luminal$ 

以后我们开发中经常会遇到这种写法,所以大家要了解、熟悉!