One of the problems with getter/setters in Flash is that you must find a location to store the protected property and all to often that area is not that protected. Often this leads to property pollution as there are now 2 variables, the getter/setter and the protected property it gets and sets. Not good.
One handy solution is to use a common function for both the getter and setter functions and store the protected property within the common function object. I have found this handy as it enforces access rules for the getter/setter and makes for much cleaner code. Actually if you delete the function reference you cannot access the private property directly.
Sample:
//define function for both getter and setter
f = function(s){
//reference to the executing function object
var self = arguments.callee
//getter
if(arguments.length <1){
//return the value
return self.privateProp
//setter
}else{
//set the value
self.privateProp = s
}
}
addProperty('publicProp',f,f)
//delete the local reference to make the property truely private and inaccessable
delete f
//set the property
publicProp = 23
//get the property
trace(publicProp)
In the above code, I delete the reference f so that access to the private property can only occur through the getter/setter. This can be very useful within a class as all instances will share a common private value within the inheritance hierarchy.
Make sure you declare a new function object for each getter/setter or many getter/setters will share the common property. If this is the behavior you want, this can be a handy way solution.
Should you choose to store the function reference f, you can always access the privateProp as follows:
f.privateProp = 45
Ahhhh, truly private properties in the Flash Player, the world is a safer place! ;)
Cheers,
ted ;)
DIGG IT! 
0 Responses to “ Truly Private Getter/Setters ”
Post a Comment