在 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 引用文献也没有描述它。
最后的问题列表:
- 为什么会这样呢?对我来说,这很奇怪,看起来像是未定义的行为;
- 我如何实现该功能?如何像匿名函数一样欺骗测试函数?不是调用目标方法吗?
这不是很重要,但我会很高兴任何好的答案。谢谢!
附注对不起我的英语。
//已编辑:将此语句添加到所有“名称”引用中。没有任何改变。
最佳答案
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/