我在 Actionscript 3 中使用 'call' 方法的示例有什么问题?

What is wrong in my example of using the 'call' method in Actionscript 3?

我正在尝试使用 AS3 自学 OOP,为此我给了自己一个挑战。因为它相当复杂,所以我试图了解 AS3 中的有用工具。

无论如何,function.call(AS3 API 的文档。here) method looks quite interesting, and I think I would be able to put that into use, however I apparently don't understand fully what it does and how it works. JavaScript seems to have an equivalent that looks pretty straightforward to use. (I saw this other thread 与我的问题相同,但在 JS 中)

这是我认为 function.call 会做的一个例子。

package
{
    import flash.display.Sprite

    public class Main extends Sprite 
    {

        public var foo:Foo;
        public var bar:Bar;

        public function Main() 
        {
            foo = new Foo();
            bar = new Bar();

            trace(bar.barProperty); //Hello World!

            //I expect the 'foo.BarProp' to be called with this==bar.
            foo.value = foo.BarProp.call(bar); //ReferenceError: Error #1069: Property barProperty not found on Main.as[=11=].Foo and there is no default value.

            trace(foo.value); //Expected output: Hello World!
        }

    }

}

class Foo {

    public var value:String;

    public function Foo() {}

    public function BarProp():String {
        return this.barProperty;
    }
}

class Bar {

    public var barProperty:String = "Hello World!";

    public function Bar() {}
}

好吧,我只是没有得到什么?

首先,return this.barProperty 应该会给您编译错误,因为在您编写该代码的 this 上没有 barProperty

其次,我不认为 Function/call() 可以改变 this 对于 class 实例方法的含义。它适用于对象函数:

var foo:Object = {
    getBarProperty: function(){
        return this.barProperty;
    }
}

var bar:Object = { // or use your Bar class
    barProperty: "Hello World"
}

trace(foo.getBarProperty.call(bar)); // "Hello World"

foo.getBarProperty(); // "undefined", because "foo" does not have a "barProperty"

这个和Javascript一样,但是Javascript没有classes和实例函数,和this is infamously not always lexical,所以用call()apply()thisArg 是更常见的做法。在大约 10 年的 ActionScript 3 开发中,我不记得曾经需要将 call() 与不同的 thisArgument 一起使用。