闭包中的箭头函数

Arrow functions in closures

为什么这有效:

var a = () => { 

    var print = function(i) { console.log(i); return this; }    
    var print2 = function(i) { console.log(i); return this; }

    return { print:print , print2:print2 }
}

a().print(5).print2(5);

这也有效:

var b = () => { 

    var print = (i) => { console.log(i); return this; }    
    return { print:print}
}
b().print('Arrow function works');

虽然这不起作用:

var b = () => { 

    var print = (i) => { console.log(i); return this; }    
    var print2 = function(i) { console.log(i); return this; }

    return { print:print , print2:print2 }
}
b().print(5).print2(5);

https://jsfiddle.net/Imabot/1gt2kxfh/14/

在非箭头函数中,this 的值取决于函数的调用方式。如果函数作为一个对象的成员被调用,this指的是这个对象:

someObj.myFunction() // inside myFunction this will point to someObj

相反,箭头函数不影响this。所以在箭头函数中 this 的值是它在封闭范围内的任何值。

这都是由于箭头函数的行为(docs)

分步说明:

var b = () => { 
    // 1
    var print = (i) => { console.log(i); return this; }    
    var print2 = function(i) { console.log(i); return this; }

    return { print:print , print2:print2 }
}
const res = b()
// 2
const secondRes = res.print(5)
// 3
secondRes.print2(5);

  1. 这里 print 函数保存了来自外部范围的 this 引用,所以 this 不能再被重新分配
  2. 现在 print 函数不使用来自 res 变量的 this 引用,因为 this 已经附加到上面的 print 函数
  3. 因此 secondRes 不会引用 b 函数返回的对象。但它将使用附加到 print 函数的 this 引用。最后因为 secondRes 没有 print2 属性 - 它抛出

希望对您有所帮助<3

Lex82 的回答给出了原因。如果你想 return 函数,那么你可以使用函数链:

var b = () => { 

    var print = (i) => { console.log(i); return { print:print , print2:print2 }; }    
    var print2 = function(i) { console.log(i); return this; }

    return { print:print , print2:print2 }
}
b().print(5).print2(5);