Star123
Star123

Reputation: 679

alternative to eval in Javascript

I have an object created which belongs to particular class.

            var schCom1 = Server.CreateObject(ArchiveProgID);

Now, this object gives call to method which is dynamically decided.

            fnName += "(";
        for (counter=0;counter<fnArgs.length;counter++)
        {
            if(counter > 0)
                fnName += ",";
            fnName += fnArgs[counter];
        }
        fnName += ")";
        writeComment("Ready to call method:" + "schCom1." + fnName);
        // according to the type of recurrance, call method
        eval("schCom1."+ fnName);   

Is there any substitution possible to this eval call ?

Any Help will be valuable .

Thanks in advance.
Tazim.

Upvotes: 1

Views: 2707

Answers (2)

slebetman
slebetman

Reputation: 113896

Provided that fnName really is a name of a method of the schCom1 object:

schCom1[fnName].apply(schCom1,fnArgs);

Basically, the apply method for function objects allow you to call the function and provide the context (parent object) and arguments. And the apply method expects function arguments to be supplied as an array, which is useful in this case.

See the documentation of the apply method for more info:

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/function/apply

there's also the call method which does something similar but expects function arguments as a regular argument list:

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/function/call

Upvotes: 3

Gabi Purcaru
Gabi Purcaru

Reputation: 31524

You can use a more simpler

schCom1[fname].apply(schCom1, fnArgs)

that would replace all your code up there

Upvotes: 2

Related Questions