使用粗箭头(将函数绑定(bind)到 this 的当前值)和将 @ 的值放在变量中有什么区别?
胖箭头
Account = (customer, cart) ->
@customer = customer
@cart = cart
$('.shopping_cart').bind 'click', (event) =>
@customer.purchase @cart
和
Account = (customer, cart) ->
@customer = customer
@cart = cart
self = @
$('.shopping_cart').bind 'click', (event) ->
self.customer.purchase self.cart
@建议使用粗箭头避免弄乱周围的范围。怎么办?
最佳答案
我对您的两个代码片段以及其他两个粗箭头解决方案进行了基准测试,我认为它们使用 CoffeeScript 的类语法时更加惯用:
class AccountWithFatCallback
constructor: (@customer, @cart) ->
$('.shopping_cart').bind 'click', (event) =>
@customer.purchase @cart
class AccountWithFatProtoMethod
constructor: (@customer, @cart) ->
$('.shopping_cart').bind 'click', @onClickCart
onClickCart: =>
@customer.purchase @cart
所有这些都是使用最新的 CoffeeScript 编译器 v1.8.0 编译的,您可以在 jsPerf 上查看基准测试.四种实现之间的性能差异很小(~5% 左右),所以我建议决定使用什么的因素应该是代码库的可读性和一致性,但我强烈建议你尝试使用 CoffeeScript 类因为他们可以为此提供很多服务。
我要提出的唯一性能警告是避免多次创建粗箭头匿名函数,如果您可以选择创建它们一次并重新使用相同的绑定(bind)函数。使用 fat-arrow 原型(prototype)方法通过在构造函数中隐式绑定(bind)一次方法来实现这一点。
关于javascript - 在变量中影响它而不是在 coffeescript 中使用粗箭头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27046007/