简体   繁体   English

在As3中,是否有一种方法可以修改函数中的类变量(如果将其作为参数传递)?

[英]Is there a way, in As3, to modify a class variable within a function, if you have a it passed as a parameter?

Here is a simple example of what I mean: 这是我的意思的简单示例:

private var ex:String="day";

......

closeWindows(ex);
trace(ex);//I would like it to trace "night"

......

//this can be in another class, we assume that the "ex" variable can't be accessed directly
private function closeWindows(context:String):void {
  context = "night"
}

Somehow I would need to pass the reference not the value itself to the "closeWindows" method. 我不知何故需要将引用而不是值本身传递给“ closeWindows”方法。

Any help it's highly appreciated. 非常感谢您的任何帮助。 Thanks. 谢谢。

AS3 doesn't support passing primitives by reference, unfortunately. 不幸的是,AS3不支持通过引用传递基元。 So you're right, one of the typical solutions is to use some kind of wrapper for the primitive, such as in this question . 因此,您是对的,一种典型的解决方案是对原始数据使用某种包装,例如在this Question中

Probably you are already aware of this, but in Actionscript parameters are always passed by value. 可能您已经意识到了这一点,但是在Actionscript中,参数始终按值传递。 So what you want to do is not possible, unless use some ad hoc wrapper (object, array, or whatever). 因此,除非使用某些临时包装(对象,数组或其他任何东西),否则您无法做任何事情。

But can't you just return and reassign the new string? 但是,您不能只返回并重新分配新字符串吗?

Thank you both for the answers, in the end it seems that there is no way to pass a variable as reference not as value. 谢谢你们两个的回答,最后似乎没有办法将变量作为引用而不是值传递。 However, you can pass a function as a reference, so here is my little get/set hack. 但是,您可以传递一个函数作为参考,因此这是我的一点“获取/设置”技巧。

private var ex:String="day";

                    ......

                    closeWindows(setEx);
                    trace(getEx());

                    ......


                    private function getEx():String {
                        return ex;
                    }

                    private function setEx(value:String):String {
                        ex = value;
                    }


                    private function closeWindows(context:Function):void {
                        context.call(null, "night");
                    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM