I'm using V8 in a C++ program for extensions. I want to be able to create objects in JavaScript that "inherit" from a base class in C++. This is a simple hierarchy in C++:
class animal
{
public:
void move();
virtual void vocalize() = 0;
};
class cat : public animal
{
public:
void vocalize() override;
void ignore_owner();
};
This is cat implemented in JavaScript instead of C++:
function cat()
{
this.vocalize = function() {}
this.ignore_owner = function() {}
}
add_animal(new cat);
where add_animal() is a global function implemented in C++:
void add_animal(v8::Local<v8::Object> o);
In add_animal(), I manually add the move property pointing to a C++
function and make sure that the vocalize property exists and is a
function.
var c = new cat;
c.ignore_owner(); // JavaScript code
c.move(); // error, undefined
add_animal(c);
c.move(); // okay, C++ code
My experience in JavaScript outside of web pages is limited. Is this a
scheme that makes sense? The fact that add_animal() is used to both
add the "base class" properties and add the animal to a list looks
counter-intuitive to me. I could add a second function:
var c = new cat;
make_animal(c);
add_animal(c);
but this requires discipline and looks convoluted.
I could also expose animal, use it to create objects and add the
cat-specific properties afterwards:
function make_cat(c)
{
c.vocalize = function() {}
c.ignore_owner = function() {}
}
var c = new animal;
make_cat(c);
add_animal(c);
but this looks weird to me.
What is the best way to "inherit" from a C++ class?