在Flex 3中,Arraycollection通过值而不是引用传递给函数

我想通过flex 3中的一个函数设置arrayCollection#2 = arrayCollection#1.我将两个数组集合传递给一个函数,并设置arrayCollection#2 = arrayCollection#1.但是,似乎没有通过引用arrayCollection#2,因为在函数调用之后,arrayCollection#2没有被改变.我的理解是,应该通过参考和工作来传递,我做错了什么?以下是代码
var AC1:ArrayCollection = new ArrayCollection;
var AC1.addItem(someObject);

var AC2:ArrayCollection = new ArrayCollection;

setAC2(AC1,AC2);
// AC2 is not set to AC1 after the function


private function setAC2(_ac1:ArrayCollection,_ac2:ArrayCollection):void
{
    _ac2 = _ac1;
}

解决方法

请参阅 Evaluation Strategy.

AS使用“通过对象”/“通过对象共享”.也就是说,“对象”被传递(不是副本,克隆或重复),并且对对象的任何修改都是共享的.

但是,赋值_ac2 = _ac1只会更改[function’s local]参数变量的值,并且在函数调用期间对任何变量都不会有任何影响.传入的唯一的东西是通过对函数调用中使用的变量(或任意表达式)的评估而得到的值(“对象”).

这是因为,如上所述,所使用的策略是“通过对象”而不是(由于文档规定“通过引用”,这意味着“通过引用的值”或只是…“通过对象“).也就是说,“通过参考”一词实际上被滥用,因此令人困惑. (它在一些语言和文档中被滥用,这是一个艰难的战斗,试图达到一个共同的意义.)

如果它真的是“通过引用”,那么为_ac2分配一个新值就会传播出去. (在提出AS如何“通过引用”之前,请参阅顶部的链接,并考虑“通过引用传递”涵盖C#的out / ref,VB的ByRef,Tsql输出和C(参考)的情况,& – 这些概念不在AS,Javascript或Java中).但是,正如原帖(和额外的自我回覆)正确指出的那样,情况并非如此 – 结论:AS不支持“通过引用”;此外,文档(混淆)使用术语“通过引用”来表示“通过对象”/“通过对象共享”.

有几种方式可以将变化传播出来,按照(我的)偏好的顺序排序:

>返回新的适用值:AC2 = doSomeTransformation(AC1).这通常是最干净的.避免副作用和惊人的代码.如果适当地包装在对象(或数组)中,则可以返回多个值.
>使用一个闭包:doSomeTransformation(_ac1,finished){…; …)的doSomeTransformation(AC1,function(newValue){AC2 = newValue})完成(_ac1)}.一般来说,当函数本身的回调“运行在上下文中”时或者以cps风格编写代码时,我通常只使用这个.
>突变一个对象(AS是“通过对象”,毕竟).这很棒,但它会奏效.
var blah = {AC2:null}; doSomeTransformation(ac1,blah); …; laterOn(blah.AC2)其中doSomeTransformation可能看起来像函数doSomeTransformation(_ac1,b){…; b.AC2 = _ac1; }.一般不推荐

快乐编码.

适用摘录,从Evaluation Strategy

“通过引用调用”:(我的主要参数“引用调用”被错误地使用是它已经具有明确的含义;某些语言(如AS和Python所采用的重载术语只是增加了混淆)

In call-by-reference evaluation (also referred to as pass-by-reference),a function receives an implicit reference to a variable used as argument,rather than a copy of its value. This typically means that the function can modify the variable used as argument- something that will be seen by its caller.

“通过对象调用”/“通过对象共享调用”:(但是注意到它承认这些术语的不一致性/本地化;“通过引用调用”一词常常被误用为暗示这些语义,的参考文献]“在一些情况下也用于同样的事情)

The semantics of call-by-sharing differ from call-by-reference in that assignments to function arguments within the function aren’t visible to the caller (unlike by-reference semantics),so e.g. if a variable was passed,it is not possible to simulate an assignment on that variable in the caller’s scope. However since the function has access to the same object as the caller (no copy is made),mutations to those objects,if the objects are mutable,within the function are visible to the caller,which may appear to differ from call-by-value semantics.

相关文章

一:display:flex布局display:flex是一种布局方式。它即可以...
1. flex设置元素垂直居中对齐在之前的一篇文章中记载过如何...
移动端开发知识点pc端软件和移动端apppc端软件是什么,有哪些...
最近挺忙的,准备考试,还有其他的事,没时间研究东西,快周...
display:flex;把容器设置为弹性盒模型(设置为弹性盒模型之后...
我在网页上运行了一个Flex应用程序,我想使用Command←组合键...