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
  • 71,301
  • 29
  • 165
  • 172

3 Answers3

7

Yes, you can use the square bracket notation.

cursor["continue"](parameters)

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

techfoobar
  • 63,712
  • 13
  • 108
  • 129
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
  • 70,503
  • 15
  • 107
  • 148
  • 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
  • 34,863
  • 6
  • 72
  • 90