简体   繁体   中英

In JavaScript, how do I access a function on an object using a string argument?

So, for example, I have one function someObject.doSomething() & another function someFunction(whatObject, whatFunction) . I want to be able to use someFunction like this: someFunction('someObject', 'doSomething') and have it call someObject.doSomething() .

Basically what I want to do is pass strings to a function that can then use those strings to call other functions.

So you have two objects, object A & B.

A.doSomething = function(){...}
B.doSomethingElse = function(){...}

Now for A to doSomethingElse, you can use call as so:

B.doSomethingElse.call(A);

This changes the this of doSomethingElse to the scope of A, which makes so the function doSomethingElse is applied on A.

Use this:

 function doIt(obj, fn){ (new Function(obj+"."+fn+"()"))(); }; var A = {b:function(){ alert("test"); }} doIt("A", "b"); 

You could execute a string as code with eval.

function execute(objectName, objectFunction){
    eval(objectName + "." + objectFunction+"();");
}

execute("anotherObject", "doSomethingElse");

But caution with this command, this might throw a exception if either the object or the function does not exist.

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