In Flash Player, when you save a reference to a member function, you can
call the function reference, and "this" will still be bound to the instance
where it came from.

public class Test
{
    public function Test()
    {
        this.func();
        var func:Function = this.func;
        func();
    }

    private function func():void
    {
        trace(this); //in Flash, "this" will always be an instance of Test
    }
}

Basically, in the code above, the two calls to func() will behave the same
in Flash Player. However, in the current implementation of the transpiler,
that behavior is lost. When the reference to func() is called, "this" ends
up referring to the global window object instead.

JavaScript function objects have a bind() function that let's you set what
"this" will refer to when the function is called:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

After modifying my code to use bind(), the two calls to func() will have
the same output:

public function Test()
{
    this["func"] = this.func.bind(this);
    this.func();
    var func:Function = this.func;
    func();
}

Would it be possible for the transpiler to automatically bind all member
functions to the correct scope to preserve the behavior that AS3 developers
expect?

- Josh

Reply via email to