Correcting teacher:天蓬老师
Correction status:qualified
Teacher's comments:箭头函数其实并不是什么新发现, python中早以有之, 所以抽空多学几门编程语言没有错的, 不少语言之间的语法中相互借鉴的
箭头函数提供了一种更加简洁的函数书写方式
基本用法及ES6类的申明
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>箭头函数</title>
<script typet="text/javascript" src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script>
</head>
<style>
.like{ font-size:35px; color:#ccc; cursor:pointer;}
.cs{ font-size:35px;color:#f00;cursor:pointer;}
span{font-size: 12px; line-height: 50%;}
</style>
<span class="like" id="dian">❤</span>
<span id="zang"></span>
<body>
<script>
// 1.无参数的箭头函数
let a1 = () => {};
console.dir(a1());
// 2.传参数的箭头函数
let a2 = (itme) => console.log(`->a2(${itme})`);
a2(25);
//3.多个参数
let a3 = (...items) => console.log(`->a3(${items})`);
a3(1,2,3,4);
//4,箭头函数的应用
let a4 = (a,b) => console.log(a + b);
a4(5,8);
//箭头函数的累加
let a5 = (...args) => args.reduce((prev,next) => prev + next,0);
//reduce函数相加后的总和
console.log(a5(9,33,44,12,5,66,44,33));
// 箭头函数的遍历
let a6 = (...items) => items.map((item)=>console.log(item));
a6("曹操","刘备","董卓");
let a7 = (d,l,m) => console.log(d+l+m);
a7(5,5,3);
a7(...[8,4,6])
let a8 = (w,...items) => console.log(w,items);
a8(5,6,7,8);
a8(...[5,6,7],8);
//5.属性的简化
let a9 = (id,name,email) => ({id,name,email});
user = a9(1,"曹操","cc@qq.com");
console.log(user);
//6.方法的简化
let a10 = {
sName : "三国演义",
getSg()
{
return this.sName;
},
};
console.log(a10);
//7.闭包应用场景
let a11 =() =>
{
let username = "曹操";
let get = () =>username;
return get;
}
let a12 = a11();
console.log(a12());
//子函数调用父函数的变量值
//8.创建多个全局可用的API
let set,inc,dec,print
let manager = (n) =>
{
let num = n;
//定义一个变量接收数值
set = (val) => {num = val};
//存储num
inc = () => { num++; return num;}
dec = () => { num--; return num;}
print = () => { return num;} ;
};
manager(10);
document.getElementById("zang").innerHTML = print();
$(function () {
$("#dian").click(function () {
if(document.getElementById("dian").className==='like')
{
document.getElementById("dian").className = 'cs';
document.getElementById("zang").innerHTML = inc();
}
else
{
document.getElementById("dian").className = 'like';
document.getElementById("zang").innerHTML = dec();
}
});
});
//9.ES6 类的申明
class UserName
{
constructor(name)
{
this.name = name;
}
setname()
{
return this.name;
}
}
username = new UserName("刘备");
console.log(username.setname());
</script>
</body>
</html>
示例图: