关于es6中的函数写法

1、函数参数的默认值

函数的参数支持默认值,如果有多个值,要传参时,只能省略最后一个

function str(x=10,y=20) {
       console.log(x, y);
};
str(100);

如果非要传y,可采用对象的形式来写

    function str({x,y=20}) {
        console.log(x, y);
    }
    //str({});//10 20
    //str();//报错
    //str({y:50});//10 50
    str({});//x没有默认值会输出undefined

2、函数参数的rest参数 把剩余的参数包装到数组里

    function arr(x,y,...args) {
        console.log(x,y,args);
        console.log(arguments);//实参个数 是object对象,也是伪数组,不能使用数组的方法
        args.forEach(function (item,i) {
            console.log(item);
        })
    }
    arr(1,2,3,4,5)//1 2 3 4 5

3、箭头函数

有两种函数的写法

  • 函数的声明–>箭头函数不能用于有名函数
  • 函数的表达式
    let add = (x,y) => {
        return x+y;
    }
    console.log(add(10, 20));//30

简写:只有一个参数,可以省略()

	let add2 = x =>{return x;}
    console.log(add2(50));//50

简写:当函数体只有一条语句时,后面表达式的值直接可以作为返回值

    let add3 = (x,y) => x+y;
    console.log(add3(10, 20));//30

匿名函数:

	var arr = [1,2,3,4];
    arr.forEach(function (item,i) {
        console.log(item);
    })

es6:

    arr.forEach((item,i) => {
        console.log(item);
    })

简写:

    arr.forEach(item => console.log(item));

4、箭头函数中的this

es5:

    function Fo() {
        console.log(this);//实例对象
        var that = this;
        setTimeout(function () {
            console.log(this);//window
            console.log(that);//实例对象
        }.bind(this),100);
    };
    var per1 = new Fo();

es6:

    function Foo() {
        setTimeout(() => {
            console.log(this);
        },1000)
    }
    var per2 = new Foo();

猜你喜欢

转载自blog.csdn.net/qq_42926749/article/details/82971872