ES6 箭头函数的演变过程和使用技巧

箭头函数:本质上也是一种函数的定义方式

1.function定义函数

//使用function定义函数
var aaa = function(){

}

function bbb(){

}

//字面量中定义函数
var ccc={
    ddd(){
    
    }
}

2.箭头函数

//1.普通式
var demo = (a,b)=>{
    return a+b;
}

//2.省略式
var sum = (a,b) => a+b;
var multi = a=> a*a;

3.箭头函数的演变过程

3.1 普通函数

function sum(a,b){
    return a+b;
}
console.log(sum(10,20));

3.2 匿名函数

setInterval(function(){
           console.log(to here);
},500);

3.3省略匿名函数前面的function

setInterval(() => {
           console.log(to here);
},500);

3.4代码块中单行语句可以省略花括号

setInterval(() => console.log(to here),500);

3.5只有一个形参的时候可以省略小括号

var nums = [1,3,5,6,7,9]
let arr = nums.map(item => item*2)
console.log(arr)

4.箭头函数的注意事项

4.1箭头函数不会执行构造函数

Normal.prototype.name=原形毕露
function Normal(){}
const normal = new Normal()
console.log(normal.name)

const Arrow = ()=>{}
const a = new Arrow()

4.2 this指向问题

例1:

<button class="normalButton">普通函数</button>
<p class="normalP"></p>
<button class="arrowButton">箭头函数</button>
<p class="arrowP"></p>
body{
  background:orange;
  display:flex;
  flex-direction:column;
  justify-content:center;
}
.normalButton,.arrowButton{
  height:60px;
  width:240px;
  line-height:60px;
  font-size:24px;
  cursor:pointer;
  margin:20px auto;
}
const normalButton = document.querySelector(".normalButton")
const arrowButton = document.querySelector(".arrowButton")
const normalP = document.querySelector(".normalP")
const arrowP = document.querySelector(".arrowP")

let normalFunction = function(){
  normalP.innerHTML = "普通函数" + this
}

let arrowFunction = () => {
  arrowP.innerHTML = "箭头函数" + this
}
normalButton.addEventListener(click,normalFunction,false)
arrowButton.addEventListener(click,arrowFunction,false)

例2:

5.JAVA篇

如果一个接口只有一个,那么这个接口也称之为函数式接口。可以使用@FunctionalInterface注解标识。

@FunctionalInterface
public interface Function {
    int plus(int i,int j);
}

当我们使用去构造内部类时,我们很简单的表示:

public class Client {
    public static void test(Function function){
        System.out.println(function.plus(1, 2));
    }

    public static void main(String[] args) {
        // 这里我们使用了内部类
        test(new Function() {
            @Override
            public int plus(int i, int j) {
                return i + j;
            }
        });
    }
}

这样写的话其实和抽象类没有什么区别,并不能体现出函数式接口的优越性

我们可以对之进行简化,

类名方法名全不要,这个结构分为两部分,第一部分,小括号包裹形参,类型也不要、第二部分 ->、第三部分是方法体

public class Client {
    public static void test(Function function){
        System.out.println(function.plus(1, 2));
    }

    public static void main(String[] args) {
        // 这里我们使用了内部类
        test((i,j)->{return i+j;});
    }
}

只有一行的返回体的话我们甚至可以省略大括号

public class Client {
    public static void test(Function function){
        System.out.println(function.plus(1, 2));
    }

    public static void main(String[] args) {
        // 这里我们使用了内部类
        test((i,j)->return i+j);
    }
}
经验分享 程序员 微信小程序 职场和发展