[英]Way to avoid CoffeeScript passing object reference style
I'm trying to copy (deep copy specifically) an object in CoffeeScript. 我正在尝试在CoffeeScript中复制(特别是深复制)对象。 Here's the problem:
这是问题所在:
class Mat
constructor: ->
@m00 = 5
@m01 = 3
mul: (b) ->
x1 = @m00
@m00 = x1 * b.m00
@m01 = x1 * b.m00
x = new Mat
x.mul(x)
alert x.m00 #25
alert x.m01 #125
So as you can see, 如您所见,
How can I instead get the copy to be a new object with the values so that changing the instance's values won't affect it? 我如何才能使副本成为具有值的新对象,以便更改实例的值不会影响它? I am trying to avoid this...
我正在努力避免这种情况...
x1 = @m00
y1 = b.m00
@m00 = x1 * y1
EDIT: Another example 编辑:另一个例子
@m00 = b.m00 * copy.m00 + b.m01 * copy.m03 + b.m02 * copy.m06
@m01 = b.m00 * copy.m01 + b.m01 * copy.m04 + b.m02 * copy.m07
@m02 = b.m00 * copy.m02 + b.m01 * copy.m05 + b.m02 * copy.m08
@m03 = b.m03 * copy.m00 + b.m04 * copy.m03 + b.m05 * copy.m06
@m04 = b.m03 * copy.m01 + b.m04 * copy.m04 + b.m05 * copy.m07
@m05 = b.m03 * copy.m02 + b.m04 * copy.m05 + b.m05 * copy.m08
@m06 = b.m06 * copy.m00 + b.m07 * copy.m03 + b.m08 * copy.m06
@m07 = b.m06 * copy.m01 + b.m07 * copy.m04 + b.m08 * copy.m07
@m08 = b.m06 * copy.m02 + b.m07 * copy.m05 + b.m08 * copy.m08
I'm still not sure what you're up to, but let's look at what the latest version of "mul" does: 我仍然不确定您要做什么,但是让我们看看“ mul”的最新版本有什么作用:
mul: (b) ->
x1 = @m00
@m00 = x1 * b.m00
@m01 = x1 * b.m00
Your code calls "mul" with "x" as both the context and the parameter ("b"). 您的代码调用“ mul”,其中“ x”作为上下文和参数(“ b”)。 Thus, the first line of code,
因此,第一行代码
x1 = @m00
sets local variable "x1" to x.m00
. 将局部变量“ x1”设置为
x.m00
。 That's the same as b.m00
, remember. 请记住,这与
b.m00
相同。
The next line of code sets x.m00
to the product of the value of "x1" times b.m00
, which if of course the same as x.m00
. 下一行代码将
x.m00
设置为“ x1”的值乘以b.m00
,如果与x.m00
相同, x.m00
。 Thus, after 因此,之后
@m00 = x1 * b.m00
the value of x.m00
(and, because "b" and "x" refer to the same object, b.m00
) is 25
. x.m00
的值(并且,因为“ b”和“ x”指向同一对象, b.m00
)为25
。
The next statement: 下一条语句:
@m01 = x1 * b.m00
sets x.m01
(and b.m01
) to the product of "x1" and the current value of b.m00
. 将
x.m01
(和b.m01
)设置为“ x1”与b.m00
当前值的b.m00
。 Well, "x1" is still 5
, because it hasn't been changed. 好吧,“ x1”仍然是
5
,因为它没有被更改。 But b.m00
is now 25
because of the previous statement. 但是由于前面的声明,
b.m00
现在为25
。 Thus, the value of x.m01
is set to 125
( 5 * 25
). 因此,
x.m01
的值设置为125
( 5 * 25
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.