0

How can I execute a Javascript function such this:

cursor.continue(parameters)

By using a string to identify the function name, without using eval? Something like this:

cursor.callMethod("continue", parameters);

Is this possible?

CodingIntrigue
  • 75,930
  • 30
  • 170
  • 176

3 Answers3

7

Yes, you can use the square bracket notation.

cursor["continue"](parameters)

cursor["continue"] is exactly the same as cursor.continue.

techfoobar
  • 65,616
  • 14
  • 114
  • 135
2

If you are in control of callMethod, and the function belongs to an object or is global, then yes, that's possible.

For example, if the target function is a method of the same object where callMethod is:

var cursor = {
    callMethod: function(method, params) {
        this[method].apply(this, params);
    },
    continue: function() {}
}
cursor.callMethod("continue", [1, 2, 3]);
bfavaretto
  • 71,580
  • 16
  • 111
  • 150
  • Unfortunately the `cursor` is an IndexedDB cursor, so techfoobar's solution is more appropriate, but definitely +1 for the literal implementation of my example method. – CodingIntrigue Jan 10 '14 at 13:52
0

Yes, you can call the function like so:

cursor["continue"](parameters);
Richard Dalton
  • 35,513
  • 6
  • 73
  • 91