1、箭头函数介绍
● 一般的函数:
<script>
var test = function(){
console.log(2222)
}
test()
</script>
● 箭头函数:
<script>
var test = () => {
console.log(2222)
}
test()
</script>
● 可以省略function,然后括号和大括号直接加一个箭头
2、箭头函数的特性:
(1)只有一个形参时,括号可以省略
<script>
//省略前
var test = (a) => {
console.log(2222,a)
}
test(100)
//省略后
var test = a => {
console.log(2222,a)
}
test(100)
</script>
(2)函数{}里只有一句代码或者只有返回值时,{}可以省略
● 只有返回值时,return也可以省略掉
<script>
//省略前
var test = (a) => {
console.log(100*a)
}
test(10)
//省略后
var test = a => console.log(100*a)
test(10)
//只有返回值
var test = a => 100*a
test(10)
</script>
● 但是当只有返回值时,而且返回值是一个对象的话,因为对象也是用{}包裹起来的,所以如果将函数的{}省略掉,到时候函数执行的时候就会认为{}是函数的,从而对象报错,所以可以在对象{}外面加上();
<script>
//省略前
var test = () => {
return {
name:"yiyi"
}
}
test()
//省略后
var test = () => ({
name:"yiyi"
})
test()
</script>
(3)箭头函数没有argument
● argument:有实参,在不写形参的情况下,在函数内部内嵌了一个函数变量就是arguments,打印出来是一个数组,不是真正的数组,是伪数组,来接收实参;
● 一般函数:有argument
<script>
var test = function(){
console.log(arguments)
console.log(arguments[0],arguments[1],arguments[2])
}
test(1,2,3)
</script>
结果:
● 可以通过Array.from(arguments)将伪数组转换为数组
<script>
var test = function(){
console.log(arguments)
console.log(arguments[0],arguments[1],arguments[2])
console.log(Array.from(arguments))
}
test(1,2,3)
</script>
● 箭头函数没有argument
<script>
var test = () => {
console.log(arguments)//报错
}
test(1,2,3)
</script>
(4) 箭头函数没有this,箭头函数this是父级作用域的,
● 一般函数:this指向
<body>
<input type="text" name="" id="mytext">
<script>
mytext.oninput = function(){
setTimeout(function(){
console.log(this.value)
},1000)
}
</script>
</body>
写一个定时器,嵌套在input事件中,此时定时器里的this指向是window,因为是window让定时器function函数执行的,所以this.value值是undefined,那如何实现this指向mytext呢,可以用新变量接收的方法:
<body>
<input type="text" name="" id="mytext">
<script>
mytext.oninput = function(){
var that = this
setTimeout(function(){
console.log(that.value)
},1000)
}
</script>
</body>
结果:
解释说明:给this赋值变量that,这样this就能指向mytext了,然后再用that获取mytext的value值,input框输入啥就结果就打印啥。
● 箭头函数:
<body>
<input type="text" name="" id="mytext">
<script>
mytext.oninput = function(){
setTimeout(() => {
console.log(this.value)
},1000)
}
</script>
</body>
结果:
解释说明:同样是定时器函数,箭头函数的this指向就是父级mytext,而一般函数是window,这也是箭头函数的一个好处,不用再去多赋值变量了。
3、ES6新增的一个功能:给函数设置默认参数
● 默认情况下:是会传参的
<script>
function fn (a,b){
console.log(a,b)
}
fn(10,20)
</script>
● 没有传参的情况下:可以给函数设置默认参数
<script>
function fn (a=1,b=2){
console.log(a,b)
}
fn()
</script>
● 在ES6中,一般给函数形参加上默认参数,这样防止忘记传参时的尴尬哈哈哈