user3682546
user3682546

Reputation:

calculation under class as3

I am absolutely a beginner in as3; I am really trying to understand how as3 works. I wrote a simple function which will multiply one number (please see the following code). I want to multiply 9 with 5 and trace it but it's not multiplying. Can anyone help me?

package  {
    import flash.display.MovieClip;
    public class main extends MovieClip {
        var xyz:int=9;

        public function main() {
            // constructor code
            mAth(xyz);
            trace(xyz);
        }
        protected function mAth(xyz:int):int{
            return(xyz*5);
        }
    }
}

Upvotes: 1

Views: 59

Answers (2)

BotMaster
BotMaster

Reputation: 2223

It's a correct answer overall but it's not the main reason why trace is not showing the expected results and since the user wants to understand the given answer does not supply a why to a perfectly valid operation.

Here is a better one:

Primitive objects in AS3 are passed by value not by reference. Those are numbers and strings. When you pass your variable xyz to your function you would expect it to be modified like in some other language but since only the value it represents is passed your variable is not modified and stay at 9. This is the default behavior of AS3 and it cannot be overridden. So you just have to remember that primitive objects in AS3 when passed as parameters in methods/functions are only passed by value and as a result do not see their value change.

in your case:

var xyz:int=9;
var result:int = mAth(xyz);
//xyz is still 9 since only its value is passed to the method
//result is 45 since it computes and return the value passed as parameter

Upvotes: 1

Malte Köhrer
Malte Köhrer

Reputation: 1579

You call the function "mAth" but don't use the results. try

trace(mAth(xyz));

to see the results of the function call.

Is there a specific reason why you pass an internal variable to a function? You can access xyz without passing the value to the mAth function.

Upvotes: 2

Related Questions