typeof operator on a .NET method returns "object" - is that correct?

Mar 26, 2014 at 11:52 AM
Hi,

Using ClearScriptConsole, I find:
-> host.Where
[HostMethod:Where]
-> typeof host.Where
object
That is, a method on a host object is not reported to be a "function", even though it can be called with (). Contrast this with the situation in IE or Chrome's debug consoles:
typeof console.log
"function"
Why is this important? Generic JavaScript utility functions often need the ability to sniff for "callable" values, which they do using typeof === "function".

I encountered this when trying to use JSON.stringify on a tree of objects, e.g. a JS array of host objects. I need to control how the host object is serialised, so (in accordance with how JSON.stringify works) I implemented toJSON as a method on my host class. But JSON.stringify uses typeof to check whether toJSON is a function. It gets the answer "object", so it does not call it.
Coordinator
Mar 26, 2014 at 8:08 PM
Edited Mar 27, 2014 at 3:16 AM
Hi danielearwicker,

What you're seeing is correct. Host objects can't masquerade as JavaScript functions.

For JSON there are several possibilities. For example, you could add a custom toJSON() method to your JavaScript array. You could also pass a replacer function to JSON.stringify().

In theory it's also possible for a host object to expose a property whose value is a script function, although that doesn't seem to work for toJSON() in V8; apparently it checks more than just the typeof string.

Finally, you can use a host object as the prototype for a wrapper to which you can add whatever you need.

Good luck!
Marked as answer by danielearwicker on 3/27/2014 at 5:41 AM