无法从静态方法获取参数数组吗?

Is it not possible to get the arguments array from a static method?

我试图从静态方法中获取保留关键字 arguments 数组,但出现此错误:

1042: The this keyword can not be used in static methods. It can only be used in instance methods, function closures, and global code.

这是我的代码:

public static function doSomething(message:String, ...Arguments):void {
    var object:Object = this.arguments.caller;
}

如果我去掉 this 关键字,则会出现以下错误:

1120: Access of undefined property arguments.

this 保留用于引用 class 的当前实例,不幸的是,它不存在于静态函数中(因为静态函数未绑定到实例)。

如果您想传入未知数量的参数,您可以尝试使用新的 rest 关键字:

ActionScript 3.0 includes a new ...(rest) keyword that is recommended instead of the arguments class.

但是,如果您只想获取调用函数:

Unlike previous versions of ActionScript, ActionScript 3.0 has no arguments.caller property. To get a reference to the function that called the current function, you must pass a reference to that function as an argument. An example of this technique can be found in the example for arguments.callee.

public function test() {
    doSomething("Hello", arguments.callee);
}

public static function doSomething(message:String, caller:Function):void {
    var object:Object = caller;
}

您可以获得静态方法的arguments。来自文档:

Within a function's body, you can access its arguments object by using the local arguments variable.

您不需要 this 关键字,this 引用 Class 实例而不是 function 本身:

public static function doSomething():void {
    return arguments;
}

接下来可以访问arguments调用静态方法:

var arguments:Object = MyClass.doSomething();
trace( arguments.callee );

但请记住,就像@MartinKonecny 所说,在 AS3 中最好使用 ...rest 关键字或传递 function 引用作为参数。

arguments 对象在静态函数中可用,但在使用 ...rest 参数时不可用。

Use of this parameter makes the arguments object unavailable. Although the ... (rest) parameter gives you the same functionality as the arguments array and arguments.length property, it does not provide functionality similar to that provided by arguments.callee. Make sure you do not need to use arguments.callee before using the ... (rest) parameter.

去掉...rest参数,出现arguments对象。

此外,this 关键字并非总是必需的。

method.apply(this, args);

可能会在静态函数中抛出错误,但参数是可选的,所以这也有效:

method.apply(null, args);

有关 rest 关键字的更多信息。