【问题标题】:Moonscript static fieldsMoonscript 静态字段
【发布时间】:2016-06-06 04:57:48
【问题描述】:

我想这样上课:

class Example
  field: false --some field shared for all instances of the class
  init: (using field) ->
    field = true --want to change value of the static field above

但在 lua 中我得到了:

<...>
field = false,
init = function()
  local field = true //Different scopes of variable field
end
<...>

在文档中我读到使用有助于处理它的写作

【问题讨论】:

    标签: lua moonscript


    【解决方案1】:

    您可以通过编辑实例中的元表来更改您所描述的值:

    class Example
      field: false
      init: ->
        getmetatable(@).field = true
    

    我不建议这样做,类字段可能是您想要使用的:

    class Example
      @field: false
      init: ->
        @@field = true
    

    在分配类字段时,您可以使用@ 作为前缀来创建类变量。在方法的上下文中,@@ 必须用于引用类,因为@ 代表实例。以下是@ 工作原理的简要概述:

    class Example
      -- in this scope @ is equal to the class object, Example
      print @
    
      init: =>
        -- in this score @ is equal to the instance
        print @
    
        -- so to access the class object, we can use the shortcut @@ which
        -- stands for @__class
        pirnt @@
    

    另外,您对using 的使用不正确。 field 不是局部变量。它是类的实例元表中的一个字段。

    【讨论】:

      猜你喜欢
      • 2021-03-03
      • 2011-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-02
      • 2017-12-26
      • 2012-03-16
      • 1970-01-01
      相关资源
      最近更新 更多