JavaScript 学习-8.JavaScript 箭头函数的使用
前言
ES6 中引入了箭头函数() =>
。箭头函数不需要使用function关键字,允许我们编写更短的函数.
箭头函数
之前使用function 定义函数
fun1 = function() {
return "Hello World!";
}
console.log(fun1()); // Hello World!
使用箭头函数() =>
格式
fun2 = () => {
return "Hello World!";
}
console.log(fun2()); // Hello World!
只有一条语句
当只有一条语句的时候,并且该语句返回一个值,我们去掉大括号和 return
关键字
fun3 = () => "Hello World!";
console.log(fun3()); // Hello World!
或者也可以返回一个表达式
a = 'hello';
b = 'world!'
fun4 = () => a+b;
console.log(fun4()); // helloworld!
箭头函数传参
当需要传参数的时候,把参数放到圆括号
fun5 = (a, b) => a+b;
console.log(fun5('hello', 'world')); // helloworld
当只有一个参数的时候,圆括号也能省略
fun6 = x => x+'world';
console.log(fun6('hello')); // helloworld
参数带默认值
当参数带默认值的时候,调用函数可以不用传参
fun7 = (x='hello') => x+'world';
console.log(fun7()); // helloworld
console.log(fun7('yoyo')); // yoyoworld
this的使用
使用箭头函数没有对 this 的绑定。
在常规函数中,关键字 this 表示调用该函数的对象,可以是窗口、文档、按钮或其他任何东西。
对于常规函数,this 表示调用该函数的对象:
// 常规函数:
hello = function() {
document.getElementById("demo").innerHTML += this;
}
// window 对象调用该函数:
window.addEventListener("load", hello); // Window
// button 对象调用该函数:
document.getElementById("btn").addEventListener("click", hello); // HTMLButtonElement
用了箭头函数,则 this 表示函数的拥有者:
// 箭头函数:
hello = () => {
document.getElementById("demo").innerHTML += this;
}
// window 对象调用该函数:
window.addEventListener("load", hello); // Window
// button 对象调用该函数:
document.getElementById("btn").addEventListener("click", hello); //Window
对于箭头函数,this 关键字始终表示定义箭头函数的对象。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2019-05-17 anyproxy学习4-Linux(Centos)搭建anyproxy环境