Be careful with this though!
Consider this code:
public dynamic class MyClass
{
private var myVar : String = "Blue!";
public function foo1() : void
{
trace("myVar = " + myVar);
}
public var foo2 : Function = function() : void
{
trace("myVar = " + myVar);
}
}
//..... Some runtime code in another class
var instance = new MyClass();
instance.foo1(); //myVar = Blue!
instance.foo2(); //myVar = Blue!
instance.foo2 = function()
{
trace("myVar = " + myVar);
}
instance.foo2(); //run time exception (myVar is not defined)
When you create a proper bound function using
function name(parms:*):ReturnType {}
You're creating an instance of the Function class that's (privately)
attached to your Class object (in this case the object named MyClass). When
you instantiate MyClass, you're creating an object that contains a different
instance of Function, that is sort of equivalent to:
{
MyClass.functionName.apply(this, parms);
}
It's a closure that ties the MyClass' original function definition to the
myClassInstance instance. Note that this isn't exactly what's going on, and
"this" isn't really the "this" that you're used to - I've just written some
pseudocode to illustrate what's going on! I don't know exactly how it works
because Adobe's documentation on the traits object is pseudo-secret and
scattered around various specs and source code repos :)
But when you define a function anonymously:
function(parms:*):ReturnType {}
You don't get the "instance to function" tying closure. Explicit references
to "this" inside your anonymous function will fail or resolve to the magic
"global" object. (it's global at the moment, but I don't think it's part of
the spec), and implicit references will resolve to global.
Now, here's hoping I explained that and didn't make matters worse :D
-Josh
On Tue, Aug 5, 2008 at 8:30 PM, Laurent Cozic <[EMAIL PROTECTED]> wrote:
> I wouldn't recommend it, but you can do it using a dynamic class:
>
> package {
> public dynamic class YourClass {
> // Define the function this way:
> this.yourFunction = function() {
> return "abcd";
> }
> }
> }
>
>
> // Then to change the function:
> var test = new YourClass()
>
> trace(test.yourFunction()); // "abcd"
>
> test.yourFunction = function() {
> return "1234"
> }
>
> trace(test.yourFunction()); // "1234"
>
>
>
> --
> Laurent Cozic
>
> Flash, Flex and Web Application development
> http://pogopixels.com
>
> ----- Original Message ----
> From: arieljake <[EMAIL PROTECTED]>
> To: [email protected]
> Sent: Tuesday, August 5, 2008 11:18:53 AM
> Subject: [flexcoders] Re: modifying a function at runtime
>
> ehem...was a little sleepy when I wrote that. I meant...
>
> Is it possible to modify the method of a class at runtime?
>
> The only way I can think of is to encapsulate the function into a
> Function property that gets called by a wrapper class method.
>
>
>
>
--
"Therefore, send not to know For whom the bell tolls. It tolls for thee."
:: Josh 'G-Funk' McDonald
:: 0437 221 380 :: [EMAIL PROTECTED]