2 Replies Latest reply on Aug 10, 2007 12:25 PM by Daniel_Snowden

    Call-by-value and call-by-reference

      Hi people,

      I've been hitting Google to come up with this simple answer but no were I could find a decent answer on this one. Can anyone tell me how I can pass a parameter by value and not by reference in Flex?

      In my main mxml file I have this model which I pass to a TitleWindow:

      [Bindable] private var preferencesModel:XML;

      private function preferencesPopup():void {
      var prefWindow:Preferences = Preferences( PopUpManager.createPopUp(this, Preferences, true) );
      prefWindow.preferencesFile = preferencesFile;
      ---> prefWindow.preferencesModel = preferencesModel;

      If I change this model in my preference popup window it also changes in my main screen, I don't want this so I would like to pass this last line by VALUE and not by REFERENCE. Any idea?

        • 1. Call-by-value and call-by-reference
          Edit: D'oh! Just reread your code and noticed that preferencesModel was an XML file. In this case, the solution is simpler:

          prefWindow.preferencesModel = preferencesModel.copy();

          That'll pass a copy of your XML to the window, instead of the original XML instance.

          In any case, my comments below still stand as far as passing by value and reference are concerned, and for custom classes, the code is still valid. :)

          ActionScript 3 follows Java style rules when passing by value and reference - i.e. primitives are always passed by value, and object are always passed by reference. To my knowledge, there is no operator to explicitly indicate passing by value and by reference in AS3.

          To remedy this, you'll need to add some sort of functionality that creates a new instance object of your class, copies all the property values from the original object to the new one, then passes back the new object.

          Lets say you add a method called 'clone' to your class:

          public function clone():PreferencesModel
          var newPrefModel:PreferencesModel = new PreferencesModel();
          newPrefModel.propertyOne = this.propertyOne;
          newPrefModel.propertyTwo = this.propertyTwo;


          return newPrefModel;

          Then, in your code above, you'd change the line in question to:

          prefWindow.preferencesModel = preferencesModel.clone();

          This way, prefWindow will reference a copy of your preferencesModel object, instead of the original.

          Hope this helps!
          • 2. Re: Call-by-value and call-by-reference
            Daniel_Snowden Level 1
            Caffeinerabbit, impressive and complete and complete anwswer, great! Thanks for the help, it works like a charm.