Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/372.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在变量中影响它,而不是在coffeescript中使用胖箭头_Javascript_Coffeescript_This_Arrow Functions - Fatal编程技术网

Javascript 在变量中影响它,而不是在coffeescript中使用胖箭头

Javascript 在变量中影响它,而不是在coffeescript中使用胖箭头,javascript,coffeescript,this,arrow-functions,Javascript,Coffeescript,This,Arrow Functions,使用fat箭头(将函数绑定到此函数的当前值)和将@的值放入变量之间有什么区别 胖箭 Account = (customer, cart) -> @customer = customer @cart = cart $('.shopping_cart').bind 'click', (event) => @customer.purchase @cart 及 建议使用胖箭头避免弄乱周围的范围。怎么做?我对您的两个代码片段以及另外两个胖箭头解决方案进行了基准测试,我觉

使用fat箭头(将函数绑定到此函数的当前值)和将@的值放入变量之间有什么区别

胖箭

Account = (customer, cart) ->
  @customer = customer
  @cart = cart

  $('.shopping_cart').bind 'click', (event) =>
    @customer.purchase @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编译的,您可以在上看到基准测试。这四种实现之间的性能差异最小(~5%左右),因此我建议使用什么的决定因素应该是代码库的可读性和一致性,但我强烈建议您尝试使用CoffeeScript类,因为它们为此提供了很多功能


我要提出的唯一性能警告是,如果您可以选择创建fat arrow匿名函数一次并重新使用相同的绑定函数,那么就避免多次创建fat arrow匿名函数。使用fat arrow原型方法通过在构造函数中隐式绑定一次方法来实现这一点。

显然,使用arrow函数要轻得多。arrow而不是fat arrow?那么胖箭头有什么好处呢?Bergi的意思是胖箭头,顺便说一句,胖箭头是用类似于
this的东西实现的。将胖箭头视为一种快捷方式。如果查看编译后的代码,胖箭头将转换为包装原始函数的函数,并绑定到
@
。它不同于第二个解决方案
self=@
。不同的实现(也不同,取决于您的CoffeeScript版本),但功能相同。这里的问题到底是什么?你不应该说“似乎慢了”,你应该用多个JavaScript引擎对它进行基准测试,并使用事实。答案很好!实际上,这四种实现之间的性能差异非常小。
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