2

如果我有这样的方法:

private function testMethod(param:string):void
{
  // Get the object that called this function
}

在 testMethod 中,我能算出是什么对象调用了我们吗?例如

class A
{
  doSomething()
  {
    var b:B = new B();
    b.fooBar();
  }
}

class B
{
  fooBar()
  {
    // Can I tell that the calling object is type of class A?
  }
}
4

5 回答 5

6

抱歉,答案是否定的(请参阅下面的编辑)。函数接收到一个特殊的属性arguments,在 AS2 中它曾经拥有caller可以大致完成您想要的操作的属性。虽然 arguments 对象在 AS3 中仍然可用,但 caller 属性已从 AS3(因此 Flex 3)中删除,因此没有直接的方法可以做你想做的事。还建议您使用 [...rest 参数]( http://livedocs.adobe.com/flex/3/langref/statements.html#..._(rest)_parameter)语言功能而不是参数.

这是关于此事的参考(搜索被调用者以找到相关详细信息)。

编辑:进一步的调查表明,可以获得当前执行函数的堆栈跟踪,所以如果你幸运的话,你可以用它做一些事情。有关更多详细信息,请参阅此博客条目此论坛帖子

博客文章的基本思想是你抛出一个错误,然后立即捕获它,然后解析堆栈跟踪。丑陋,但它可能对你有用。

博客文章中的代码:


var stackTrace:String;

try { throw new Error(); }
catch (e:Error) { stackTrace = e.getStackTrace(); }

var lines:Array = stackTrace.split("\n");
var isDebug:Boolean = (lines[1] as String).indexOf('[') != -1;

var path:String;
var line:int = -1;

if(isDebug)
{
    var regex:RegExp = /at\x20(.+?)\[(.+?)\]/i;
    var matches:Array = regex.exec(lines[2]);

    path = matches[1];

    //file:line = matches[2]
    //windows == 2 because of drive:\
    line = matches[2].split(':')[2];
}
else
{
    path = (lines[2] as String).substring(4);
}

trace(path + (line != -1 ? '[' + line.toString() + ']' : ''));
于 2008-10-11T22:26:03.960 回答
4

重要的是要知道 stackTrace 仅在 Flash Player 的调试器版本上可用。对不起!:(

于 2009-01-27T22:01:46.427 回答
1

我赞成明确传递“callingObject”参数的想法。除非您正在做非常棘手的事情,否则调用者最好能够提供目标对象。(对不起,如果这看起来很明显,我不知道你想要完成什么。)

于 2008-10-12T00:20:10.033 回答
1

在 James 的第一段中添加一些模棱两可的内容: arguments 属性在 Function 对象中仍然可用,但 caller 属性已被删除。

这是文档的链接:http: //livedocs.adobe.com/flex/3/langref/arguments.html

于 2008-10-12T07:23:49.960 回答
1

这可能对某人有帮助,我不确定......但如果有人使用,Event则可以使用e.currentTarget以下方法:

private function button_hover(e:Event):void
{
      e.currentTarget.label="Hovering";
}
于 2009-06-06T01:07:55.607 回答