JavaScript----箭头函数

2018-11-15  本文已影响0人  AuglyXu

简化代码

let say = (name) => {return name}
let say = (name) => return name
let say = name => return name
let say = name => name

修改this

function Person() {
        this.age = 666;
        var self = this;

         setTimeout(function () {
            console.log(this); // window
            console.log(self);
         }, 1000);

        setTimeout(()=>{
            console.log(this); // Person
        }, 1000);
        /*
        1.由于Person构造函数也是一个函数, 所以也会开启一个作用域
        2.由于箭头函数是在Person构造函数的作用域中定义的, 所以数据Person构造函数作用域
        3.箭头函数也是一个函数, 所以也会开启一个作用域
        4.在箭头函数中使用this时, 会从所在的作用域链的上一层继承this

        应用场景:
        1. 让setTimeout/setInterval中的this变为我们想要的this
         */
    }
    function Student() {
        this.age = 666;
        // this.say = function () {
        //     // 谁调用就是谁
        //     // 可以被call/apply/bind方法修改
        //     console.log(this); //student
        // }
        this.say = ()=>{
            // 从上一级的作用域继承
            // 不可以被call/apply/bind方法修改
            // 因为箭头函数自己没有this
            // 因为箭头函数中的this只看定义, 不看调用
            console.log(this);//student
        }
    }
    var stu = new Student();
    stu.say();
    // stu.say.call({name:"lnj"});

    // 注意点:
    // 箭头函数中不能使用arguments
    // function test() {
    //     console.log(arguments);
    // }
    let test = () => {
        console.log(arguments);//报错
    };
    test(1, 3, 5);
上一篇 下一篇

猜你喜欢

热点阅读