简体   繁体   中英

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.

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

You can use a more simpler

schCom1[fname].apply(schCom1, fnArgs)

that would replace all your code up there

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM