Running instanceof from C++ given a class name as a string

99 views
Skip to first unread message

Gonzalo Diethelm

unread,
Jun 21, 2018, 2:00:04 AM6/21/18
to v8-users
I run the following JS code in the Chrome console:

// Version 67.0.3396.87 (Official Build) (64-bit)

function Car(make) { this.make = make }
var car = new Car('Ferrari')
car
instanceof Car // returns true

Now, on my C++ code I get ahold of car (by looking "car" up in the global context), and want to run the equivalent instanceof code, given only the class name "Car" as a string.  Notice that I do not have a C++ class / function backing up Car.

Just to make it clear, compiling and running "car instanceof Car" as JS code in my C++ code, works totally fine.

I naively tried to do something like this, which didn't work:

Local<Object> object = FindObject("car"); // this works
Local<FunctionTemplate> ft = FunctionTemplate::New(isolate);
Local<String> name = String::NewFromUtf8(
    isolate
, "Car", NewStringType::kNormal).ToLocalChecked();
ft
->SetClassName(name);
if (ft->HasInstance(object)) {
   
// this never happens
}

How can I do this, without manually compiling / running JS code?

Thanks!

Jakob Kummerow

unread,
Jun 21, 2018, 5:28:51 PM6/21/18
to v8-users
Well, if you're creating a new FunctionTemplate, then of course your existing "car" object isn't an instance of that new class ;-)

Value::InstanceOf is the C++ equivalent of JavaScript "instanceof":

Local<Value> object = Local<Value>::Cast(FindObject("car"));  // Assuming "car" is, indeed, a Value. Check first if needed.
Local<Object> car_class = FindObject("Car");
object->InstanceOf(context, car_class);  // Should return Just(true). Throws if car_class is not a function.

--
--
v8-users mailing list
v8-u...@googlegroups.com
http://groups.google.com/group/v8-users
---
You received this message because you are subscribed to the Google Groups "v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to v8-users+u...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Gonzalo Diethelm

unread,
Jun 22, 2018, 1:56:37 AM6/22/18
to v8-users
This works perfectly. I knew I was being naive, thank you Jakob for pointing me in the right direction!
Reply all
Reply to author
Forward
0 new messages