Actionscript 3 introspection - имена функций - PullRequest
3 голосов
/ 30 июля 2009

Я пытаюсь перебрать каждого из членов объекта. Для каждого члена я проверяю, является ли это функцией или нет. Если это функция, я хочу получить ее имя и выполнить некоторую логику на основе имени функции. Я даже не знаю, возможно ли это вообще. Это? Любые советы?

пример:

var mems: Object = getMemberNames(obj, true);

for each(mem: Object in members) {
    if(!(mem is Function))
        continue;

    var func: Function = Function(mem);

    //I want something like this:
    if(func.getName().startsWith("xxxx")) {
        func.call(...);
    }

}

Мне трудно найти что-то подобное. Спасибо за помощь.

Ответы [ 3 ]

4 голосов
/ 30 июля 2009

Ваш псевдокод близок к тому, что вы хотите. Однако вместо использования getMemberNames, который может получать закрытые методы, вы можете зацикливать элементы с помощью простого цикла for..in и получать значения элементов с помощью скобок. Например:

public function callxxxxMethods(o:Object):void
{
  for(var name:String in o)
  {
    if(!(o[name] is Function))
      continue;
    if(name.startsWith("xxxx"))
    {
      o[name].call(...);
    }
  }
}
0 голосов
/ 20 июля 2011

Я проделал некоторую работу и объединил оба подхода. Имейте в виду, это работает только для публично видимых членов - во всех остальных случаях возвращается значение null.

    /**
     * Returns the name of a function. The function must be <b>publicly</b> visible,
     * otherwise nothing will be found and <code>null</code> returned.</br>Namespaces like
     * <code>internal</code>, <code>protected</code>, <code>private</code>, etc. cannot
     * be accessed by this method.
     * 
     * @param f The function you want to get the name of.
     * 
     * @return  The name of the function or <code>null</code> if no match was found.</br>
     *          In that case it is likely that the function is declared 
     *          in the <code>private</code> namespace.
     **/
    public static function getFunctionName(f:Function):String
    {
        // get the object that contains the function (this of f)
        var t:Object = getSavedThis(f); 

        // get all methods contained
        var methods:XMLList = describeType(t)..method.@name;

        for each (var m:String in methods)
        {
            // return the method name if the thisObject of f (t) 
            // has a property by that name 
            // that is not null (null = doesn't exist) and 
            // is strictly equal to the function we search the name of
            if (t.hasOwnProperty(m) && t[m] != null && t[m] === f) return m;            
        }
        // if we arrive here, we haven't found anything... 
        // maybe the function is declared in the private namespace?
        return null;                                        
    }

Greetz,

токсикодендрон

0 голосов
/ 22 декабря 2010

Дэн Монего отвечает на деньги, но работает только для динамичных участников. Для любых членов с фиксированным экземпляром (или статических) вам необходимо использовать flash.utils.describeType:

var description:XML = describeType(obj);

/* By using E4X, we can use a sort of lamdba like statement to find the members
 * that match our criteria. In this case, we make sure the name starts with "xxx".
 */
var methodNames:XMLList = description..method.(@name.substr(0, 3) == "xxx");

for each (var method:XML in methodNames)
{
    var callback:Function = obj[method.@name];
    callback(); // For calling with an unknown set of parameters, use callback.apply
}

Используйте это вместе с ответом Дэна, если у вас есть сочетание динамических и фиксированных членов.

...