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

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

问题描述

在CoffeeScript中构建类时,应使用 => (fat arrow)运算符定义所有的实例方法,并使用定义的所有静态方法 - > 运算符?

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?

推荐答案

我会使用。

我发现在定义方法的fat-arrow的主要用例是当你想使用一个方法作为回调和方法引用实例字段:

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"

正如你所看到的,实例的方法作为回调,如果你不使用fat-arrow。这是因为fat-arrow将对象的实例绑定到 this ,而细箭头不会,因此上面称为回调的thin-arrow方法不能访问实例的 @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天全站免登陆