Ted Patrick > { Events & Community } > Adobe Systems


From AS2 it is difficult to use a common function using implicit "function get" & "function set" getter/setter syntax. Using a common function enables private variables within the getter/setter and avoids duplicate variables. The only way to accomplish this is within the AS2 class constructor, unless there is a solution I don't know about.

AS2 example:Source
//class file Widget.as

class Widget {
//constructor
function Widget(d){
//define function for both getter and setter
var f = function(s){
//reference to the executing function object
var self = arguments.callee

//getter
if(arguments.length <1){
return self.privateProp

//setter
}else{
self.privateProp = s
}
}
//set an inital value via setting the function
f(d)
//add a getter/setter to the instance
addProperty('user',f,f)
}
}
Now this is far from perfect as you loose the benefits of strict typing at compile-time but it works. AS2 syntax simply masks the AS1 addProperty method at compile-time. It is unfortunate that you cannot declare a single function for both getter/setter as follows:
function get user = function set user = function(){}
Here is an interesting use of the private getter/setter technique. This getter/setter masks a private array. As you "set" values items are pushed onto the private array and as you "get" the value items are popped off the array and returned. This is an easy way to provide a history as a single property without executing array methods.

Source
f = function(s){

//reference to the executing function object
var self = arguments.callee

//if the array does not exist create it
if(self.a ==undefined) self.a = []

//getter
if(arguments.length <1){
//pop and item off the array
var r = self.a.pop()
trace("Undo : " + r)
//return the value
return r

//setter
}else{
trace("Do : " + s)
//push an item onto the array
self.a.push(s)
}
}
//create the history getter/setter
addProperty('history',f,f)
//delete the reference limiting access through the getter/setter
delete f

history = "Wake Up"
history = "Shower"
history = "Brush Teeth"
history = "Make Bed"
history = "Make Coffee"
history = "Cook Bacon"

// Forgot to get dressed undo 3 steps
// Simply evaluating the variable pops a value off the private array
history
history
history

history = "Get Dressed"
history = "Make Bed"
history = "Make Coffee"
history = "Cook Bacon"

// I shouldn't have gotten up today
history
history
history
history
history
history
history
Way cool eh!

Comments and feedback are always welcome!

Cheers,

ted ;)

0 Responses to “ AS2 Private Getter/Setter Values and Getter/Setter Private Array Example ”

Post a Comment



Jobs


Flex Jobs
city, state, zip


© 2008 Ted On Flash