Search code examples
actionscript-3functioncallthis

Function.call( thisObject ) not working on AS3


I have a very simple code here that explains the difference I found between AS2 and AS3 when using the call method of a function.

var a = {name:"a"}
var b = {name:"b"}

function c()
{
    trace(this.name)
}


c()         // AS2: undefined   AS3: root1
c.apply(a)  // AS2: a           AS3: root1
c.apply(b)  // AS2: b           AS3: root1

How can I force AS3 to respect the thisObject argument in AS3?

Here is Adobe Documentation "http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Function.html#apply()"

Thanks


Solution

  • It's important to recognize that Functions are different from Methods. Methods are bound to the objects that they are defined in, whereas Functions are not bound to any object.

    When you are using apply or even call on a method you are extracting it from its instance, but it will always be bound to the object.

    So in your example if c() is inside an object, that is why you are not seeing thisObject change.

    From adobe on Methods:

    Methods are functions that are part of a class definition. Once an instance of the class is created, a method is bound to that instance. Unlike a function declared outside a class, a method cannot be used apart from the instance to which it is attached

    Now if you want to be able to change the thisObject you can create a function outside of the object and pass the new thisObject parameter. Here's a very basic example:

    class myClass {
        public function myBoundFunction():void {
            trace( "Bound to: " + this );
        }
    }
    
    //declared outside the class
    function unboundFunction():void {
        trace( "Unbound: " + this.name );
    }
    

    Then instantiating and applying the functions with thisObject parameter:

    var c:myClass = new myClass();
    //bound function call
    c.myBoundFunction.apply( this );
    
    //unbound call  
    unboundFunction.apply( this );
    

    Output:

    Bound to: [object myClass]
    Unbound: root1