Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
365 views
in Technique[技术] by (71.8m points)

flash - Function.apply not using thisArg parameter

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)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Its not a "bug", but the documentation for call and apply is very misleading and doesn't do a good job at all of explaining whats going on. So here is an explaination of what is happening.

Methods are different from Functions in ActionScript. Methods are defined as a part of a class defintion, and methods are always bound to that instance. See the Methods second of this link. To quote from there:

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.

So when you make a new instance of MyObj, all of its methods are bound to that instance. Which is why when you try to use call or apply, you aren't seeing this getting overridden. See the section on Bound Methods for details.

See, this document for an explanation of the traits object, which actionscript uses to resolve methods and used for performance reasons behind the scenes is probably to blame. That or class methods are just syntactic sugar for the following ECMAScript pattern:

var TestClass = function(data) {
    var self = this;
    this.data = data;
    this.boundWork = function() {
        return self.constructor.prototype.unboundWork.apply(self, arguments);
    };
};

TestClass.prototype.unboundWork = function() {
    return this.data;
};

Then:

var a = new TestClass("a");
var b = new TestClass("b");

alert(a.boundWork()); // a
alert(b.boundWork()); // b

alert(a.unboundWork()); // a
alert(b.unboundWork()); // b

alert(a.boundWork.call(b)); // a
alert(a.boundWork.call(undefined)); // a

alert(a.unboundWork.call(b)); // b

or even more interesting:

var method = a.unboundWork;
method() // undefined. ACK!

Vs:

method = a.boundWork;
method() // a. TADA MAGIC!

Notice that boundWork will always get executed in the context of the instance it belongs to, no matter what you pass in for this with call or apply. Which, in ActionScript, this behavior is exactly why class methods are bound to their instance. So no matter where they are used, they still point at the instance they came from (which makes the actionscript event model a little more "sane"). Once you understand this, then a work-around should become obvious.

For places where you want to do some magic, avoid the ActionScript 3 based hard-bound methods in favor of prototype functions.

For example, consider the following ActionScript code:

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, []); // a
            objA.sayName.call(objB); // a

            objA.pSayName.call(objB) // b <---
        }
    }
}

internal dynamic class MyObj
{
    private var _name:String;
    public function MyObj(name:String)
    {
        _name = name;
    }   
    public function sayName():void
    {
        trace(_name);
    }

    prototype.pSayName = function():void {
        trace(this._name);
    };
}

Notice the declaration difference between sayName and pSayName. sayName will always be bound to the instance it was created for. pSayName is a function that is available to instances of MyObj but is not bound to a particular instance of it.

The documentation for call and apply are technically correct, as long as you are talking about prototypical functions and not class methods, which I don't think it mentions at all.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...