前言
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 关键字始终表示定义箭头函数的对象。
本网站每日更新互联网创业教程,一年会员只需98,全站资源免费下载点击查看会员权益
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。