Monday, June 09, 2008

Hi,
Found this in a new JavaScript book (Douglas Crockford's 'JavaScript the Good Parts' [O'Reilly]) converted it to AS3 and wanted to
share, this little object blows my mind, read it over and I'll
explain below.


var myObject:Object = function() : Object {
var value = 0;
return {
increment: function (inc:Number = 1) {
value += inc;
},
getValue: function() {
return value;
}
}
}();

myObject.increment();
trace(myObject.getValue()); // traces: 1
myObject.increment();
trace(myObject.getValue()); // traces: 2


There's a few odd things here, we are able to persist the value of a
variable from inside of an object and run calculations on it. This is
the same thing as creating a class and then defining a class level
variable inside of it. We are then defining functions inside of this
returned object that can use these persistent variables.

Other odd things, notice the last line of the myObject definition. We
are executing the function right away, personally I never seen this
before but opens my mind a little further into the way that objects
interact and what calling a function really means.

This all runs in AS3 but if you go into this to deeply I personally
wouldn't want to step in and work on that code. I think this is more
interesting to show how objects can interact and what is happening
and how things can be passed around.

Thanks to J-C for sending this over to me. If you don't fully
understand it's cool but we should cover some of this at a fcny meeting
some day. There are other ideas in that book that will blow your mind even further
but I'll spare you for now, this one just has stuck in my mind and I
wanted to share.

-Tyler
Zemanta Pixie

Labels: , ,

0 Comments:

Post a Comment

Links to this post:

Create a Link

<< Home