Closures和CoffeeScript的作用域 [英] Closures and CoffeeScript's Scoping

查看:194
本文介绍了Closures和CoffeeScript的作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码定义了两个函数 lines circles ,返回一个函数 f g 。函数 f g 是相等的(() - > size )只是为了简单,但通常它们是变量 size 的不同函数。

The following code defines two functions, lines and circles, that return a function, f and g respectively. Functions f and g are equal (() -> size) only for simplicity, but in general they are different functions of the variable size.

lines = () ->
    size = 10 # default value
    f = () -> size
    f.size = (_) ->
      size = _
      f
    f

circles = () ->
    size = 15 # default value
    g = () -> size
    g.size = (_) ->
      size = _
      g
    g

代码结果如下模式,这是我需要的:

On the console, the above code results on the following pattern, which is what I need:

> lines()() # 10
> lines().size(20)() # 20
> circles()() # 15
> circles().size(30)() #30

$ c> f.size 和 g.size 方法都是闭包,它们在行上是相同的圈子。然后我的问题是:如何避免复制 size 方法的代码(使用coffeescript或javascript)

As you may note, the f.size and g.size methods are closures and they are the same on both lines and circles. Then my question is: how I can avoid to duplicate the code for the size method? (with coffeescript or javascript)

我尝试了不同的解决方案,但我没有找到正确的方法。为了复制闭包, size 方法中的 size 变量应该引用 )的第一行定义

I tried different solutions, but I did not find the right way. In order to replicate the closure, the size variable inside the size method should refer to the size variable defined at the first line on lines (and the same holds for circles).

推荐答案

您不能在的代码中使用辅助函数,可以按预期访问closure变量。但是,您可以将整个代码包装在一个函数中,以便它分别返回 circle / p>

You can't use a helper function in your code, as that won't have access to the closure variable as expected. However, you can wrap your whole code in a function so that it returns you the lines or circles function respectively:

make = (def, accessor) ->
    () ->
        size = def
        f = () -> accessor size
        f.size = (_) ->
           size = _
           f
        f

lines = make 10, (size) -> size
circles = make 15, (size) -> size

这篇关于Closures和CoffeeScript的作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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