【问题标题】:With function in Coffee Script咖啡脚本中的功能
【发布时间】:2014-10-17 17:26:38
【问题描述】:

下面的代码可以咖啡脚本吗?

With pex
  .simpleObject = {}
  .explicitFunction = ()->
     alert "Hello world!"
  .CONSTANTPI = 3.16
Endwith

请忽略with 中的内容。我只是指如何在咖啡脚本中做到这一点?而不是重复输入单词pex.

【问题讨论】:

    标签: coffeescript


    【解决方案1】:

    由于JavaScript的with语句不应该使用,最好用嵌套函数和this访问器来实现:

    _with = (object, block) -> block.call object
    
    _with pex, ->
      @simpleObject = {}
      @explicitFunction = ()->
        alert "Hello world!"
      @CONSTANTPI = 3.16
    

    【讨论】:

      【解决方案2】:

      您可以编写一个小辅助函数,因为您的目标似乎是将属性分配给一个对象,这个就足够了:

      addprops = (obj, addthis) ->
        for own key,value of addthis
          obj[key] = value
      
      pex = {}
      
      addprops pex,
        simpleObject:     {}
        explicitFunction: ()->
          alert "Hello world!"
        CONSTANTPI:       3.16
      
      console.log pex
      
      ###
      OUTPUT:
      { simpleObject: {},
        explicitFunction: [Function],
        CONSTANTPI: 3.16 }
      ###
      

      你也可以看看那里的几个mixin libraries之一。

      【讨论】:

      • for key of addthis then if addthis.hasOwnProperty(key) then ...可以写成for own key of addthis then ...
      猜你喜欢
      • 2018-11-06
      • 2012-10-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-09
      • 1970-01-01
      • 2012-08-26
      • 2013-09-08
      • 1970-01-01
      相关资源
      最近更新 更多