[webkit-help] Find out if a given JSValueRef is of a certain built-in class (Array, Date, Error, …)

Marco Masser marco at duckcode.com
Mon Feb 4 08:20:56 PST 2013

Hey there,

I found the solution thanks to "andersca" in the IRC chatroom (#webkit on irc.freenode.net):
The context's global object has the constructors as properties (e.g. this.Array). These can then be used in a call to JSValueIsInstanceOfConstructor().



> Hello,
> I'm looking for a way to find out if a given JSValueRef is, for example, an Array or a Date.
> I know that JSValueIsObjectOfClass() is the function I'm looking for, but what I don't know is what I should pass in as the JSClassRef value if it's not one of my own classes. I searched the JavaScriptCore public API, but there doesn't seem to be a way to get a JSClassRef to the built-in classes.
> Is there some other way to find the class of a given object?
> I tried the following approach, but that just doesn't seem right to me:
> • Call JSGlobalContextCreate()
> • Store a pointer to the prototype JSValueRef:
>     arrayPrototype = JSObjectGetPrototype(JSObjectMakeArray())
> • To check if an arbitrary JSObjectRef is an Array:
>     arrayPrototype == JSObjectGetPrototype(object)
> I'm using JavaScriptCore as it comes installed on OS X 10.8.2 (WebKit 4, if I'm reading the headers right).
> A little more detail about what I'm really trying to do:
> I wrote some Objective-C classes that makes it easy for what I want to do. I'm converting various JavaScript types to the appropriate Foundation classes (Boolean/Number -> NSNumber, String -> NSString, …).
> I'd also like to bridge arbitrary classes (that I'm writing the necessary support code for). For example, if a JavaScript function returns an Array, I'd like to convert it to an NSArray. If it returns an Error, I'd like to convert it to an NSError. If it returns an MyJavaScriptFoo, I'd like to convert it to an MyObjectiveCFoo.
> For this to work, I must know that kind of JSObjectRef I'm getting. I simply know that the JSType is kJSTypeObject, but there doesn't seem to be a way to simply get the class of an object.
> Thanks in advance,
> Marco

More information about the webkit-help mailing list