1 Reply Latest reply on Apr 15, 2007 4:55 PM by mforsberg

    set calls get

    Voxar
      Hi.
      I browsed and searched the forum but "set" and "get" really isn't good searchphrases so I didnt find any topics on this, thou I'm sure it has been discussed before.

      I'm quite curious about the extra call to get method when using set.
      Imagine this class:
      class Foo{
      private var _bar:String="";
      public function get bar(){
      trace("GET");
      return _bar; }
      public function set bar(value:String){
      trace("SET");
      _bar = "#"+value;}
      }

      Using it like this:
      foo = new Foo();
      foo.bar = "Hello";
      trace(foo.bar);

      produces the following output:
      SET
      GET
      GET
      #Hello

      Why is the set method calling the get method?
      After having some problems with this I stumbled across a discussion at http://www.darronschall.com/weblog/archives/000071.cfm. The comentators there suggests that it is due to chain assignments and that you would like to pass on the checked and possibly modified version of the value(!), but still the following code:
      foo = new Foo();
      var a:String = foo.bar = "Hello";
      trace(a);

      outputs:
      SET
      GET
      Hello

      So I really don't see the point in calling the get method from set at all.

      Any thoughts or explanations?

      Pretty print of the class code:
        • 1. set calls get
          mforsberg
          if accessing foo.bar did not "get" it then

          foo = new Foo();
          var a:String = foo.bar = "Hello";
          trace(a);

          would output:
          SET
          undefined

          and that would be a nightmare :(

          are you having some kind of problem due to this?

          on a sidenote; i wouldn't really recommend using setters and getters at all in classes since they always seem to create quite the performance issue. however, i'm pretty sure this is not due to the fact that a set does a get, since it does this even without set/get functions defined :)