[英]Object not being passed by reference (CoffeeScript)
I have two classes, one which holds and manages data and one which makes decisions based on the data 我有两类,一类负责保存和管理数据,一类根据数据进行决策
module.exports = class Data
constructor: () ->
@stuff =
foo: 42
bar: 'something'
and in another file 并在另一个文件中
module.exports = class Mutator
constructor: (Data) ->
@foo = Data.foo
and in a main file 并在主文件中
Data = require './Data'
Mutator = require './Mutator'
module.exports = class Main
constructor: () ->
@data = new Data()
@mutator = new Mutator(@data)
the problem I'm having is that @data
does not seem to be being passed by reference 我遇到的问题是
@data
似乎没有通过引用传递
In main 在主要
console.log @Mutator.foo # 42
@data.foo = '24'
console.log @Mutator.foo # still 42
What could be causing this? 是什么原因造成的?
@data
is being passed by reference but you're throwing that reference way when you pull out the Data.foo
value here: @data
通过引用传递,但是当您在此处提取Data.foo
值时,您将抛出该引用方式:
@foo = Data.foo
Your Data
is the same as your @data
but @foo
is just the value of Data.foo
. 你的
Data
是一样的@data
但@foo
是只值Data.foo
。 You'd need to hold onto Data
rather than Data.foo
: 您需要保留
Data
而不是Data.foo
:
class Mutator
constructor: (Data) ->
@data = Data
and then look at @mutator.data.foo
. 然后查看
@mutator.data.foo
。 You could probably use defineProperty
to define a getter for foo
and thus hide the data
part and make @mutator.foo
work. 您可能可以使用
defineProperty
为foo
定义一个getter,从而隐藏data
部分并使@mutator.foo
起作用。 Have a look at this answer for some notes on how this would work. 请查看此答案,以获取有关其工作原理的一些注释。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.