Quantcast
Channel: Adobe Community: Message List - ColdFusion
Viewing all articles
Browse latest Browse all 21760

Setters in a component

$
0
0

Hi,

 

I made the mistake of not scoping a local variable in a component's function. The variable had the same name as one of the propeties in the component, and that had the unexpected effect of overwriting the value of the property. In other words, forgetting to properly scope the variable made it behave like a setter.

 

I know the solution is to use the right scope in each situation. However, I would expect to handle the properties only by using getters and setters, so I would like to know why does that overwrite the property, as it feels completely unexpected to me.

 

Have a look at the example, I hope it will make the question clearer.

 

Thanks!

 

Xavier

 

 

Component:

component     displayname="myComponent"     accessors="true"     persistent="true"
{     property name="foo" type="string" default="bar";          function init(){          return THIS;     }          function usingSetter(required string newValue){          setFoo(ARGUMENTS.newValue);     }          function doSomething(){          // do something not related to the property. I just happen to name a local variable as 'foo'          var foo = 'foobar';          return true;     }          function doSomethingElse(){          // do something not related to the property. I just happen to name a local variable as 'foo', without the var keyword          foo = 'choo';          return true;     }
}

 

Page:

     myComponentInstance = new myComponent();     writeDump(var=myComponentInstance, label="Just initialized myComponent. Property has default value");          myComponentInstance.usingSetter('qux');     writeDump(var=myComponentInstance, label="Normal way of setting the value of the property");          myComponentInstance.doSomething();     writeDump(var=myComponentInstance, label="That doesn't change the value of the property");          myComponentInstance.doSomethingElse();     writeDump(var=myComponentInstance, label="I would NOT expect that to update the value of the property, but it actually behaved like a setter. Why?");

 

Output:

setter.png


Viewing all articles
Browse latest Browse all 21760

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>