Inheriting from a C ++ class to JavaScript
I am 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 a property move
pointing to C ++ and make sure the property vocalize
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 with JavaScript outside of web pages is limited. Does this circuit make sense? The fact that is add_animal()
used for both add the "base class" properties and add the animal to the list. counter-intuitive to me. I could add a second function:
var c = new cat;
make_animal(c);
add_animal(c);
but it takes discipline and looks confusing.
I could as well open animal
, use it to create objects, and add the
cat
-specific properties:
function make_cat(c)
{
c.vocalize = function() {}
c.ignore_owner = function() {}
}
var c = new animal;
make_cat(c);
add_animal(c);
but it looks strange to me.
What is the best way to "inherit" from a C ++ class?
source to share
Just show your JavaScript base class (see the official implementation guide for an example) and then use regular JavaScript inheritance:
function Cat(name) {
this.name = name;
}
var catproto = Cat.prototype = new Animal();
catproto.vocalize = function() { /* cat-specific override */ }
catproto.ignore_owner = function() { return true; /* :-P */ }
catproto.purr = function() { /* you can add new methods too */ }
var c = new Cat("Kitty");
c.move(); // Inherited.
c.vocalize(); // Meow.
source to share