actionscript-3 - Function.call(someInstance,args) 用于方法。忽略第一个参数

标签 actionscript-3 call this

在 as3 中,有一种灵活的方法可以在调用对象实例时更改它。 Function 对象的 call 或 apply 成员可以使用特定的第一个参数来调用,并且引用告诉我们,第一个参数将是函数内的“this”指针。但我发现这是错误的。

我编写了一些测试,如下所示。

public class Test 
{
  private var name:String = "default";
  public var test3:Function = test;
  public var test2:Function = function()
  {
    trace(this.name);
  }

  public function Test(name:String) 
  {
    this.name = name;
  }

  public function test():void
  {
    trace(this.name);
  }
}

并进行了测试。

var tmp:Test = new Test("default");
tmp.test();  //out default
tmp.test.call(new Test("new"));  //out default

tmp.test2(); //out default
tmp.test2.call(new Test("new2")); //out new2

tmp.test3(); //out default
tmp.test3.call(new Test("new3")); //out default

因此,在匿名函数调用中我们可以获得正确的输出,但在成员函数的情况下则不然。 也许是因为不明确的“this”指针,应该引用真实的对象实例以进行正确的工作,也许还有别的。我现在不知道了,as3 引用文献也没有描述它。

最后的问题列表:

  1. 为什么会这样呢?对我来说,这很奇怪,看起来像是未定义的行为;
  2. 我如何实现该功能?如何像匿名函数一样欺骗测试函数?不是调用目标方法吗?

这不是很重要,但我会很高兴任何好的答案。谢谢!

附注对不起我的英语。

//已编辑:将此语句添加到所有“名称”引用中。没有任何改变。

最佳答案

When invoking the [[Call]] property, the behavior is different for different types of closures. A closure is an object that contains a reference to a method, and the [[Call]] property acts differently depending on whether it is a function, method, or class closure. A function closure is one that is of a global method that isn't associated with any instance of a class. A method closure contains an instance method of a class, and will always remember its original "this" value.

If the closure is a function closure, then the first argument passed to [[Call]] is passed on to the method and gets used as the "this" value. If the first argument is null or undefined, then the global object will be used as the "this" value for the method.

If the closure is a method closure, then the first argument of [[Call]] will be ignored, and the saved "this" value for the method closure will be passed to the method as the first argument. A method closure records what its original "this" value was and always uses that instead of the first argument to [[Call]].

If the closure is a class closure, and there is 1 argument passed to [[Call]] (in addition to the "this" argument), then the call is treated as a type conversion, and the argument will be coerced to the type represented by the closure.

http://learn.adobe.com/wiki/display/AVM2/2.4+Method+invocation+notes

关于actionscript-3 - Function.call(someInstance,args) 用于方法。忽略第一个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11977341/

相关文章:

actionscript-3 - AS3 禁用 Datagrid 内 textInput 的可编辑/可选择

Python:这两个函数有什么问题?

javascript - 使用 this 从嵌套函数内部获取值

actionscript-3 - MouseEvent.RIGHT_CLICK 在运行时未定义?

flash - 捕获 Flash URLLoader 错误

Java:使用actionlistener在另一个类中的对象上调用该类中的函数

javascript - 如何在 JavaScript 中使用关键字 "this"进行 DOM 操作

javascript - 为什么 not($(this)) 之后的回调函数会重复多次?

flash - 我如何在 flex 中以 MX 数据网格列的百分比设置宽度?

javascript - 关于更改运行 javascript 函数的上下文