【问题标题】:In AS3, how can you store, retrieve and reuse arguments provided by an ellipsis (...) parameter?在 AS3 中,如何存储、检索和重用省略号 (...) 参数提供的参数?
【发布时间】:2012-11-19 22:49:14
【问题描述】:

我有一个继承自 NetConnection 的类,具有以下功能:

override public function connect(command:String, ... arguments):void
{
    addEventListener(NetStatusEvent.NET_STATUS, onNetStatus);
    super.connect(command, arguments);
}

我想要做的实际上是这样的:

override public function connect(command:String, ... arguments):void
{
    m_iTries = 0;
    m_strCommand = command;
    m_arguments = arguments;
    addEventListener(NetStatusEvent.NET_STATUS, onNetStatus);
    super.connect(command, arguments);
}

private function onNetStatus(pEvent:NetStatusEvent):void
{
    if (/* some logic involving the code and the value of m_iTries */)
    {
        super.connect(m_strCommand, m_arguments);
    }
    else
    {
        // do something different
    }
}

这在 AS3 中可能吗?如果是这样,怎么做?我将如何声明变量、设置变量、将其传递给函数等?谢谢!

【问题讨论】:

  • 你是说你上面的代码行不通吗?我从来没有尝试过,但你上面的代码是我期望它工作的方式。 arguments 参数是 Array,因此您只需声明一个成员变量 (private var m_argument:Array),并按照您所做的那样分配它。唉,看起来简单的东西实际上可能行不通:)
  • 它看起来不能工作。不过谢谢! “如果您传递 Array 类的实例,则整个数组将被放入 ...(rest)参数数组的单个元素中。” help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/…
  • 好的,我现在明白了,谢谢你的解释......现在我明白了,我会考虑这个:)
  • 您需要使用 Function.apply() 使其按书面方式工作,例如super.connect.apply(super, m_arguments); - 允许您像传递参数列表一样传递数组。但请注意,您必须先将“命令”添加到数组中,然后再将其传递给 super.connect.apply。
  • @TheKaneda 好电话,您应该将其发布为答案!

标签: actionscript-3 apache-flex syntax flash


【解决方案1】:

connect 中的类似内容:

 ...
 // Add m_strCommand to the start of the arguments array:
 m_arguments.unshift(m_strCommand); 
 ...

onNetStatus:

if (/* some logic... */)
{
    // .apply calls the function with first parameter as the value of "this". 
    // The second parameter is an array that will be "expanded" to be passed as 
    // if it were a normal argument list:
    super.connect.apply(this, m_arguments);
}

这意味着调用例如(虚假的论点):

myNetConnection.connect("mycommand", 1, true, "hello");

将导致来自onNetStatus 的调用:

super.connect("mycommand", 1, true, "hello");

更多关于.apply()http://adobe.ly/URss7b

【讨论】:

    猜你喜欢
    • 2019-09-10
    • 2017-08-18
    • 2013-06-27
    • 1970-01-01
    • 2019-03-06
    • 2011-03-09
    • 2014-09-06
    • 1970-01-01
    • 2018-09-02
    相关资源
    最近更新 更多