JavaScript 第十章总结:first class functions
前言
这一章的内容是 advanced knowledge and use of functions. 讲了关于 function 的使用的一些特殊的方面。
function expression 的定义
格式:
var fly = function(num){
for(var i = 0; i < num; i++) {
console.log("Flying!");
}
};
fly(3);
与 function declaration 的两个不同之处
- runtime 不同:function declaration 是在浏览器执行代码之前先进行扫描,并创建相应的函数,function expression 是在浏览器执行代码的时候进行创建相应的函数。
- function naming 方式不同: function declaration 是将 reference 赋值给函数名,而使用 function expression 不需要 provide a name.
关于第二点,书中最后总结:
- When the browser evaluates a function declaration, it creates a function as well as a variable with the same name as the function, and stores the function reference in the variable.
- When the browser evaluates a function expression, it creates a function, and it's up to you what to do with the function reference.
使用 function 的三种特殊的情况
定义
first class values: function 可以作为 value 来使用,书中的描述如下:
First class: a value that can be treated like any other value in a programming language, including the ability to be assigned to a variable, passed as an argument, and returned from a function.
功能:
- Assign a value to a function
- Pass a function to a function
- Return a function from a function
无论是 function declaration 还是 function expression, 它们的名字都是函数的 reference 值,因此可以利用、传递这个值来 invoke 一个 function.
1. Assign the value to a function
格式:var fly = [function expression]
2.Pass the function to a function
格式:function boo(aFunction){
aFunction("boo");
}
function fun(echo){
}
boo(fun);
3. Return a function from a function
使用 sort() 这个 method
sort() 介绍:
sort 可接受一个数字作为参数,通过这个参数的情况进行排序:
- >0的时候:place the first item after the second item
- =0的时候: leave the items in place
- <0 的时候:place the first item before the second item
总结的两种情况:
可以使用一个自定义的 compare(num1,num2) 函数,来得到上面所要求的参数,并且分下面两种情况:
- ascending:if(num1>num2){return 1;}或者 return(num1-num2)
- descending:if(num1<num2){return 1;}或者 return(num2-num1)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具