箭头函数this 精简几句

56 阅读1分钟

箭头函数的 this 始终指向函数定义时的 this,而非执行时。

箭头函数中没有 this 绑定,必须通过查找作用域链来决定其值,如果箭头函数被非箭头函数包含,则 this 绑定的是最近一层非箭头函数的 this,否则,this 为 undefined

var a = { 
    func2: function () { 
    setTimeout( () => { 
        this.func1() },100); 
    } }; 
    a.func2() // Cherry

等效于↓

var a = { 
    func2: function () { 
    setTimeout( function() { 
        this.func1() }.apply(a),100); 
    } }; 
    a.func2() // Cherry

bind需要自调用↓

this.func1() }.bind(a)(),100);