es6 函数的扩展

代码:

<script>
    //默認值的用法
    /*     function log(x, y) {
            y = y || "word";
            console.log(x, y);
        }
        log("hello");
     */
    /*     function add(...values) {

            let sum = 0;
            for (let val of values) {
                sum += val;
            }
            return sum;
        }
        console.log(add(1, 2, 3, 4, 5, 5, 5, 5));
     */

    /*     function foo(n) {
            return n;
        } */

    //=====> 等價于 let foo = n => n;

    /*     //1個參數的時候
        let add = value => value;
        //2個參數
        let add2 = (value1, value2) => value1 + value2;
        let add3 = (value1, value2) => {
            value1 += 1;
            let sum = value1 + value2;
            return sum * 100;
        }
        console.log(add(1), add2(1, 2), add3(1, 2)); */

    /*     let PageHandle = {
            id: 123,
            init: function() {
                document.addEventListener('click', (event) => {
                    console.log(this);
                    this.doSomeThings(event.type);
                }, false); //正常的funtion(event){}如果函數沒有bind函数绑定上面的this,this指向,會指到#document,但是箭头函数没有这个问题。
            },
            doSomeThings: function(type) {
                console.log(`事件類型:${type},當前id:${this.id}`);
            }
        };
        PageHandle.init(); */

    //箭頭函數不能用new來實例化
    //错误示例:
    let fn = () => 1;
    let newFn = new fn();
    //上面代码报错,报错显示:Uncaught TypeError: fn is not a constructor,面试题。
    


    //箭頭函數沒有this指向問題;
</script>

1,箭头函数函数体中 this 的指向是定义时 this 的指向。如代码中

PageHandle.init定义时的this,就是PageHandle这个对象。
箭头函数版:
    let PageHandle = {
            id: 123,
            init: function() {
                document.addEventListener('click', (event) => {
                    console.log(this);
                    this.doSomeThings(event.type);
                }, false); //正常的funtion(event){}如果函數沒有bind函数绑定上面的this,this指向,會指到#document,但是箭头函数没有这个问题。
            },
            doSomeThings: function(type) {
                console.log(`事件類型:${type},當前id:${this.id}`);
            }
        };
        PageHandle.init(); 

function 版:需要用bind函数绑定定义时的对象,代码如下:

    let PageHandle = {
            id: 123,
            init: function() {
                document.addEventListener('click', function (event) {
                    console.log(this);
                    this.doSomeThings(event.type);
                }.bind(this), false); //正常的funtion(event){}如果函數沒有bind函数绑定上面的this,this指向,會指到#document,但是箭头函数没有这个问题。
            },
            doSomeThings: function(type) {
                console.log(`事件類型:${type},當前id:${this.id}`);
            }
        };
        PageHandle.init(); 

其他笔记:可能面试会问到的。

//箭頭函數不能用new來實例化
    //错误示例:
    let fn = () => 1;
    let newFn = new fn();
    //上面代码报错,报错显示:Uncaught TypeError: fn is not a constructor,面试题。
原文地址:https://www.cnblogs.com/Dmail/p/13193113.html