1

In JavaScript, let's say you have:

function doSomething(callback) {
    if (callback instanceof Function) callback();
}

doSomething(function() {
    alert('hello world');
});

Is there a way to check what is inside 'callback' (like, the fact that alert() is called) from doSomething()? Something like:

function doSomething(callback) {
    alert(callback.innards().indexOf('alert('));
}

I'm just curious

tjb1982
  • 2,257
  • 2
  • 26
  • 39

4 Answers4

2

Function.prototype.toString() gives an implementation-dependent representation of the function. However built-in functions will return something like:

function Array() {
   /* [native code] */
}

and host methods can return anything, even throw an error. So the strict answer is yes, maybe. But in a practical sense, it is not reliable.

RobG
  • 142,382
  • 31
  • 172
  • 209
1

Some browsers support toString() on functions.

function doSomething(callback) {
    console.log( callback.toString().indexOf('alert(') )
    if (callback instanceof Function) callback();
}
epascarello
  • 204,599
  • 20
  • 195
  • 236
  • `Some browsers`? It's in [ECMA-262](http://es5.github.com/#x15.3.4.2) so I would expect all browsers to support it. Do you know of any browser that doesn't? – RobG May 24 '12 at 01:55
  • @Saxoier duh, it is a text match. It is not going to be accurate. And you missed `var foo = "alert()";` – epascarello May 24 '12 at 02:11
  • And i 'missed' `alert (` and 1000 other possibilities. – Saxoier May 24 '12 at 02:15
  • @RobG should be good for all modern day browsers, brain does not remember if IE6 supports it and I am not going to whip open a VM to test it. – epascarello May 24 '12 at 02:15
0

You should be able to say:

alert( callback.toString().indexOf('alert(') );

However that won't distinguish between the beginning of a function alert(, the beginning of a function myspecialalert(, and the text "alert(" if it happens to be in a string literal - so you may need to do a bit of parsing.

Not sure how cross-browser this is, but in Firefox at least .toString() returns the whole text of the function including the word "function" and the parameter list.

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
0
callback.toString().indexOf('alert(');

OR do a regex match like:

/alert *\(/.test(callback.toString());
xdazz
  • 158,678
  • 38
  • 247
  • 274