【问题标题】:coffeescript how i can instantiate attribute咖啡脚本我如何实例化属性
【发布时间】:2016-03-31 02:44:58
【问题描述】:
class Foo
  list: []
foos = []
for i in [1..2]
  foos.push new Foo
foos[0].list.push "a"
foos[1].list.push "a"
console.log foos[0].list
console.log foos[1].list

此代码输出为:

["a", "a"]
["a", "a"]

但我不明白为什么没有输出:

[“一个”] [“一”]

似乎 foos[k].list 是静态参数!

【问题讨论】:

    标签: arrays class coffeescript


    【解决方案1】:

    是的,list 值在所有 foo 实例之间共享。

    看看生成的 JS 对你有意义吗?

    Foo = (function() {
      function Foo() {}
    
      Foo.prototype.list = [];
    
      return Foo;
    
    })();
    

    如果我对您的理解正确,也许这是解决您问题的有效方法:

    class Foo
      constructor: ->
        @list = []
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-01-09
      • 1970-01-01
      • 2012-08-20
      • 1970-01-01
      • 2011-11-22
      • 2017-10-01
      • 1970-01-01
      相关资源
      最近更新 更多