开发者

How to make variable act like reference in AS3 [duplicate]

开发者 https://www.devze.com 2023-03-29 14:26 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: Can you have "ByRef" arguments in AS3 functions?
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Can you have "ByRef" arguments in AS3 functions?

Primitive types in AS3 pass by value instead of reference. Is there a way to override that behavior and pass by reference for certain variables? Take the following code:

for (var i=0; i<4; i++) {
    for (var j=0; j<4; j++) {
        if(i==0 && j==0){
            switch(currentRotation){

            case 0:
                var1 = j; //I want var 1 to be a reference to j, not the value of j
                    break;

            }
        }
        if(someArray[var1][var2]){
            //stuff
       开发者_如何转开发 }
    }
}

If this isn't possible, I guess I'll just have to copy and paste the code a few times. :/

Thanks


You may cheat a bit. Wrap j into some object:

var obj = {j: 0};
for (var i=0; i<4; i++) {
    while (obj.j < 4) {
        if(i==0 && obj.j==0){
            switch(currentRotation){

            case 0:
                //...
                    break;

            }
        }
        if(someArray[var1][var2]){
            //stuff
        }
        obj.j++;
    }
}


No, primitive types could only be passed by value.


Primitive types in AS3 are actually passed by reference but they are immutable so behave as if they were passed by values.

For readers interested in the technical details, ActionScript stores primitive values internally as immutable objects. The fact that they are stored as immutable objects means that passing by reference is effectively the same as passing by value. This cuts down on memory usage and increases execution speed, because references are usually significantly smaller than the values themselves.

http://help.adobe.com/en_US/ActionScript/3.0_ProgrammingAS3/WS5b3ccc516d4fbf351e63e3d118a9b90204-7f9c.html

And so you wont be able to override this behaviour.

0

精彩评论

暂无评论...
验证码 换一张
取 消