简体   繁体   中英

V8: implement equality test

How can I redefine == operator in V8 for my own classes? For example:

var v = Foo.BAR;
var other = getBar(); // returns a new instance of the same as Foo.BAR

assert(v == other); // I want true

The functions are defined in C++ with V8, not directly in JS. I know it's possible as it has been done for the String class.

V8 developer here.

I know it's possible as it has been done for the String class.

Of course a JavaScript engine can and does define what all the operators do -- that is its job. So I wouldn't say that the == operator has been re defined for strings; it has merely been defined .

If you're willing to modify V8, then you can change the behavior of the == operator. But that's going to be a lot of work, because there isn't just one place where it's defined: you'll have to touch the C++ runtime (start by looking at v8::internal::Object::Equals ), the Ignition interpreter (look for TestEquals in src/interpreter/interpreter-generator.cc ), and the Turbofan compiler (grep for kJSEqual in src/compiler/ and adapt how it's handled in the various phases, most notably JSTypedLowering::ReduceJSEqual but there are probably other places you'll have to touch as well).

Be aware that this is a massive project; IMHO it is not advisable to go down this path. A particular difficulty will be to get the information you need (specifically, "is this object an instance of one of the classes in question?") to all the places where you'll need it; I don't have a good suggestion for how to accomplish that. Another challenge is that porting your changes to new V8 versions will be quite time-consuming maintenance work.

My recommendation would be to go for a .equals function, defined on precisely the classes that should have it. That's clean and simple, easily maintainable/adaptable, and unsurprising to any other JavaScript developer (including your own future self) reading your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM