ES6的箭头函数
ES6允许使用箭头函数,语法类似java中的lambda表达式
let fun1 = function(){} //普通的函数声明
let fun2 = ()=>{} //箭头函数声明
let fun3 = (x) =>{return x+1}
let fun4 = x =>{return x+1} //参数列表中有且只有一个参数,()可以省略不写
let fun5 = x => console.log(x) //方法体中只有一行代码,{}可以不写
let fun6 = x=> x+1 //方法体中只有一行代码且是return返回的结果,那么return可以不写
//箭头函数中的this是外层上下文环境中的this
let person ={
name:"zhangsan",
showName : function(){
console.log(this.name) // zhangsan
},
viewName:()=>{
console.log(this.name) // 空白 this===window对象
}
}
person.showName()
person.viewName()
箭头函数中this
一个简单测试Demo,主要验证箭头函数中的this是外层上下文环境中的this,页面点击后依次变红、绿,但不会黄。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#fangkuai {
display: inline-block;
width: 100vw;
height: 100vh;
background-color: rgb(67, 67, 194);
}
</style>
<script>
onload = function () {
var divElement = document.getElementById("fangkuai")
divElement.onclick = function () {
console.log(this === divElement) //true this对象是本函数调用对象,即divElement
let _this = this
this.style.backgroundColor = "red"
window.setTimeout(function () {
console.log(this === window) //true this对象是本函数调用对象,即window
_this.style.backgroundColor = "yellow"
}, 2000)
window.setTimeout(() => {
console.log(this === divElement) //true this对象是外层上下文环境中(divElement的onclick函数内)的this,即divElement
this.style.backgroundColor = "green"
}, 4000)
}
}
</script>
</head>
<body>
<div id="fangkuai"></div>
</body>
</html>
rest和spread
rest参数,在形参上使用,和java中的可变参数几乎一样;spread参数,在实参上使用rest,可以理解为rest的逆运算。
以下案例介绍了基本使用,其中合并对象比较常用。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
// rest 剩余的,解决剩余的参数接受问题
let fun1 =(a,b,c,d,...arr)=>{
console.log(a,b,c,d)
console.log(arr)
}
//...arr是形参,使用数组接收剩余参数
fun1(1,2,3,4,5,6,7,8,9) //打印结果:1,2,3,4 [5,6,7,8,9]
// spread 使用
let arr1 = [1,2,3]
let fun2 = (a,b,c)=>{
console.log(a,b,c)
}
//arr1是实参,对应形参a
fun2(arr1) // [1,2,3],undefined,undefined
//...arr1是实参,会将数组内容分解到形参,可以理解为rest的逆运算
fun2(...arr1) // 1,2,3
//spread快速合并数组
let a = [1,2,3]
let b = [4,5,6]
let c = [7,8,9]
let d = [a,b,c] //[1,2,3],[4,5,6],[7,8,9]
let e = [...a,...b,...c] // [1,2,3,4,5,6,7,8,9]
console.log(d)
console.log(e)
//spread快速合并对象
let person1 = {name:"zhangsan",id:"000001"}
let person2 = {age:10}
let person3 = {gender:"boy"}
let person = {...person1,...person2,...person3}
let person5 = {person1,person2,person3}
console.log(person) //{ "name": "zhangsan","id": "000001", "age": 10, "gender": "boy"}
console.log(person5) //{ "person1": {"name": "zhangsan","id": "000001"},"person2": {"age": 10},"person3": {"gender": "boy"}}
</script>
</head>
<body>
</body>
</html>
运行结果如下: