1. 程式人生 > >es6——函式擴充套件

es6——函式擴充套件

1.形參設定預設值

es5

       {
            function sum1(num1, num2) {
                num1 = num1 || 10;
                num2 = num2 || 10;
                console.log(num1 + num2);
            }

            sum1(20, 30);//50
            sum1();//20
        }

es6(好處:簡潔)

        {
            function sum2(num1 = 10, num2 = 10)
{
console.log(num1 + num2); } sum2(20, 30);//50 sum2();//20 }

2.引數形式 結合 延展操作符

es5

        {
            function sum3() {
                let result = 0;
                for (let value of arguments) {
                    result += value;
                }
                console.log(result);
            }

            sum3(10
,20,30);//60 }

es6(好處:可以多樣化定義傳入引數,而不是全在arguments裡不好區分)

      {
            function sum4(name,sex,...nums) {
                let result = 0;
                for (let value of nums) {
                    result += value;
                }
                console.log(result);
                console.log(name,sex);
            }

            sum4('lucy'
,'man',10,20,30,100);//160; lucy man }

3.箭頭函式 () => {}

        {
            let sum = (num1, num2) => {
                console.log(num1 + num2);
            };

            sum(100, 200);//300

            let nameArr = ['bob', 'lucy', 'tom'];
            nameArr.forEach((value, index) => {
                console.log(index + ':' + value);//0:bob; 1:lucy; 2:tom
            })
        }

無需考慮this指標不明確

     {
            //希望指向obj
            function demo1() {
                setTimeout(function () {
                    console.log(this);//Window
                }, 1000);
            }

            let obj = {};
            demo1.call(obj);
        }
        {
            //解決方法
            function demo2() {
                setTimeout(() => {
                    console.log(this);//{}
                }, 1000);
            }

            let obj = {};
            demo2.call(obj);
        }