ES6学习笔记三:增强的函数

277 阅读3分钟

1.函数的参数带默认值

默认值是一个数值

		//es5 给参数默认值
        function add(a, b) {
            a = a || 10;
            b = b || 20;
            return a + b;
        }
        console.log(add()); //20

        //es6
        function add1(a = 10, b = 20) {
            return a + b;
        }
        console.log(add1()); //30

        function add2(a = 10, b = 20) {
            return a + b;
        }
        console.log(add2(1)); //21 按顺序给参数赋值

默认值是一个函数

 		function add3(a, b = getVal(5)) {
            return a + b;
        }
        function getVal(val) {
            return 5 + val;
        }
        console.log(add3()); //a 为undefined b=10 相加 =NaN
        console.log(add3(2)); //12  -->2+(5+5)

2.剩余参数 ...keys

将多个独立的值合并到一个数组中

es6中的...keys代替arguments ...keys代表所有剩余的参数,而arguments代表所有的参数

        function pick(obj) {
            let result = Object.create(null);
            for (let i = 1; i < arguments.length; i++) { //arguments 需要排除前面的参数
                result[arguments[i]] = obj[arguments[i]];
            }
            return result;
        }
//...keys剩余参数
        function pick1(obj, ...keys) {
            let result = Object.create(null);
            for (let i = 0; i < keys.length; i++) { //用...keys直接遍历剩下的参数
                result[keys[i]] = obj[keys[i]];
            }
            return result;
        }
        const book = {
            title: "es6",
            author: "hattie",
            year: 2020
        }
        let bookData = pick(book, "author", "year");
        let bookData1 = pick1(book, "author", "year");
        console.log(bookData);
        console.log(bookData1);

...keys是真实的数组(可以直接使用数组的方法) arguments是伪数组

 		function checkArgs(...args) {
            console.log(args); //(3) ["a", "b", "c"] 真实的数组
            console.log(arguments); //Arguments(3) ["a", "b", "c", callee: (...), Symbol(Symbol.iterator): ƒ] 伪数组
        }
        checkArgs('a', 'b', 'c');


        let fn3 = (...res) => (res);
        console.log(fn3(1, 2, 3)); //[1, 2, 3]

3.扩展运算符...

将一个数组分割,各个项作为分离的参数传给函数

 		const arr = [2, 3, 1, 7];
        //es5利用apply将arr数组中的值分割,传给Math.max()
        console.log(Math.max.apply(null, arr)); //7
        //es6利用...扩展运算符 将数组中的值分割
        console.log(Math.max(...arr)); //7

4.箭头函数 =>

1.function(){} 等于()=>{return 表达式} 或 ()=>(表达式)

一般用{},能写成一排的,省略return关键字的表达式可用().

		// let fn0 = (id, name) => {
        //     return {
        //         id,
        //         name
        //     }
        // }
        let fn0 = (id, name) => ({id,name}); //返回一个对象
        console.log(fn0(1, "hattie"));

2.立即执行函数与闭包

		//立即执行函数
        let fn = (function() {
            console.log("hello");
        })();

        //  闭包函数
        let fn1 = (function() {
            return function() {
                console.log("world");
            }
        })();
        console.log(fn1);
        // 立即执行函数 return一个函数
        // ƒ () {
        //         console.log("world");
        //     }

        //闭包箭头函数
        let fn2 = (() => {
            // return () => {
            //     console.log("hello");
            // }
            return () => (console.log("hello2"))
        })();
        fn2(); //hello2

3.(参数)=>{返回值} 不论函数体有没有return关键字,{}中的内容都是返回值

普通函数function(){},用log打印函数调用时,没有返回值,则打印undefined。

		let fn4 = function() {
            2 + 3;
        }
        console.log(fn4());//undefined

        let fn5 = () => (3);
        console.log(fn5()); //3

5.箭头函数没有作用域,不改变this指向

1.不用箭头函数,用bind绑定this到调用对象上

        let pageHandle = {
            id: 123,
            // init: function() {
            //     document.addEventListener('click', function(event) {
            //         console.log("此处的this指向:" + this); //点击页面时,此处的this指向:[object HTMLDocument] 不是pageHandle对象
            //     })
            // }
            init: function() {
                document.addEventListener('click', function(event) {
                        console.log("此处的this指向:" + this); //点击页面时,此处的this指向:此处的this指向:[object Object] pageHandle对象
                    }.bind(this)) //bind改变this指向 将函数调用者的this传入 内部的this就指向函数调用者
            }
        };
        pageHandle.init();
  1. 用箭头函数,箭头函数没有作用域 //1.对象中的方法,不用箭头函数定义 //2.对象中的方法内部的函数用箭头函数,不产生作用域,不改变this指向。
        let page = {
            id: 123,
            init: () => {
                document.addEventListener('click', (event) => {
                    console.log(this); //Window {}
                    this.do(event.type); //this.do is not a function.
                  //do方法属于page而不是window,用指向window的this去调用时,会报错。
                }, false)
            },
            do: function(type) {
                console.log(`事件类型:${type},当前id:${this.id}`);
            }
        }
        page.init();

6.箭头函数注意事项

1.箭头函数内部没有arguments

        let fn8 = (a, b) => {
            console.log(this); //Window {}
            console.log(arguments); //arguments is not defined
            return a + b;
        }
        fn8();

2.构造函数不能用箭头函数来代替

普通函数是一个对象

但箭头函数只是一个表达式、语法糖,不是对象,不能new

		let Person = function(id, name) { //此处Person的P语法上可大写可小写,为了语义,需要大写
            this.id = id;
            this.name = name
        };
        let p = new Person(1, "hattie");
        console.log(p);

        let Person1 = () => {

        }
        let p1 = new Person1(); //Person1 is not a constructor