4

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?

2
  • This is really not a straightforward problem, as C++ and Javascript inheritance mechanisms have fundamental differences. This by itself might be an "architecture smell" hinting that it's not a good idea to do this. Commented Jul 18, 2015 at 19:59
  • Which is why "inherit" in is quotes. I need a simple way to create a javascript object with predefined properties while being easy to extend. Commented Jul 18, 2015 at 20:02

1 Answer 1

1

Just expose your base class to JavaScript (see the official embedder's 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.
Sign up to request clarification or add additional context in comments.

1 Comment

I had completely forgotten this question! This pet project (no pun intended) of mine is long gone, so I can't test this, but I'll accept your answer nonetheless.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.