I'm writing some Actionscript3 code that attempts to apply a method to an object that is determined at runtime. The AS3 documentation for Function.apply and Function.call both indicate that the first argument to those functions is the object which will be used as the 'this' value when the function is executed.
However, I have found that in all cases when the function being executed is a method, the first parameter to apply/call is not used, and 'this' always refers to the original object to which that method was bound. Here is some example code and its output:
package
{
import flash.display.Sprite;
public class FunctionApplyTest extends Sprite
{
public function FunctionApplyTest()
{
var objA:MyObj = new MyObj("A");
var objB:MyObj = new MyObj("B");
objA.sayName();
objB.sayName();
objA.sayName.apply(objB, []);
objA.sayName.call(objB);
}
}
}
internal class MyObj
{
private var _name:String;
public function MyObj(name:String)
{
_name = name;
}
public function sayName():void
{
trace(_name);
}
}
Output:
A
B
A
A
A minor modification to the above code to create an in-line anonymous function which refers to 'this' shows that the correct behavior occurs when the function being applied/called is not a bound method.
Am I using apply/call incorrect when I attempt to use it on a method? The AS3 documentation specifically provides code for this case, however:
myObject.myMethod.call(myOtherObject, 1, 2, 3);
If this is indeed broken, is there any work-around besides making the target methods into functions (which would be quite ugly, in my opinion)?