CoffeeScript,何时在箭头 (->) 上使用粗箭头 (=>),反之亦然 [英] CoffeeScript, When to use fat arrow (=>) over arrow (->) and vice versa

查看:16
本文介绍了CoffeeScript,何时在箭头 (->) 上使用粗箭头 (=>),反之亦然的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 CoffeeScript 中构建类时,是否应该使用 =>(胖箭头")运算符定义所有实例方法,使用 -> 定义所有静态方法; 运算符?

When building a class in CoffeeScript, should all the instance method be defined using the => ("fat arrow") operator and all the static methods being defined using the -> operator?

推荐答案

不,这不是我会使用的规则.

No, that's not the rule I would use.

我在定义方法时发现的粗箭头的主要用例是当您想将方法用作回调并且该方法引用实例字段时:

The major use-case I've found for the fat-arrow in defining methods is when you want to use a method as a callback and that method references instance fields:

class A
  constructor: (@msg) ->
  thin: -> alert @msg
  fat:  => alert @msg

x = new A("yo")
x.thin() #alerts "yo"
x.fat()  #alerts "yo"

fn = (callback) -> callback()

fn(x.thin) #alerts "undefined"
fn(x.fat)  #alerts "yo"
fn(-> x.thin()) #alerts "yo"

如您所见,如果您不使用粗箭头,则可能会遇到将实例方法的引用作为回调传递的问题.这是因为粗箭头将对象的实例绑定到 this 而细箭头没有,因此上述作为回调调用的细箭头方法无法访问实例的字段,例如 @msg 或调用其他实例方法.最后一行是使用细箭头的情况的解决方法.

As you see, you may run into problems passing a reference to an instance's method as a callback if you don't use the fat-arrow. This is because the fat-arrow binds the instance of the object to this whereas the thin-arrow doesn't, so thin-arrow methods called as callbacks as above can't access the instance's fields like @msg or call other instance methods. The last line there is a workaround for cases where the thin-arrow has been used.

这篇关于CoffeeScript,何时在箭头 (->) 上使用粗箭头 (=>),反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆