dt1000
dt1000

Reputation: 3732

as3 non-explicit function pointer

Please see code below. I will have a bunch of elements, that I want to run whatever "formula" refers to, for that element. In the code, where it says, "this works", it works as expected. However I need to fire off these formulas, without naming "firstElement" explicitly. Even though the nested for loop is a little clunky, I think it should work, but it causes the error listed below. How can I fire off the formulas, without naming the elements explicitly? Thanks!

    var test:Object = { 
        element:
        [
            { "firstElement":
                {   
                    formula:myFunction
                }
            }
        ]
    }// end test object


    public function RunThisFunctionFirst() {

        test.element[0].firstElement.formula();//this works 

        for (var index in test.element){
            for (var object in test.element[index]){
                trace ("object " + object);// traces "firstElement", as expected
                object.formula()// this causes error: Error #1006: value is not a function.
            }
        }
    }

    function myFunction (){
        trace ("my function called");

    }

Upvotes: 1

Views: 167

Answers (3)

Patrick
Patrick

Reputation: 15717

Using a for each loop you can simplify your loop, and as previously said don't forget to typed your variable :

for each (var elm:Object in test.element) {
    for each (var obj:Object in elm) {
        var formula:Function = obj.formula as Function
        if (formula!=null) formula()
    }
}

Upvotes: 2

mrk
mrk

Reputation: 5117

Regarding the outer loop, element is an array, not an object, so you want to use for(;;) not for in.

Regarding the inner loop, object is the string "firstElement" not an object.

for (var i:int=0; i < test.element.length; i++)
{
    for (var key:* in test.element[i])
    {
        trace("key " + key);
        var object:* = test.element[i][key];
        trace("object " + object);
        if(typeof object === "object" && object.hasOwnProperty("formula"))
            object.formula();
    }
}

Upvotes: 0

jcsf
jcsf

Reputation: 373

Your variable object, in (var object ... ) is not a typed variable. The compiler will default this to an Object class, which of course is not a Function class. Try casting object as a Function. I'm guess that you have extended myFunction from Function class.

either by: for (var object:Function in test.element[index])

or for (var object:myFunction ... ) // if myFunction is extended from Function

Upvotes: 1

Related Questions