ftk / quickjspp

QuickJS C++ wrapper

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

JavaScript inheritance from C++ class

ratalaika opened this issue · comments

Hello,

Im trying to make an extended Point class that inherits from our C++ Point class, something like this on C++ side:

	GFX.class_<Point>("Point")
		.constructor<double, double>()
		.fun<&Point::x>("x")
		.fun<&Point::y>("y");

And this on JS side:

function Point() { this.initialize.apply(this, arguments); }\
Point.prototype = Object.create(GFX.Point.prototype);
Point.prototype.constructor = Point;
Point.prototype.initialize = function(x, y) { GFX.Point.call(this, x, y); };
Point.emptyPoint = new Point(0, 0);

This seems to flop due to "JS_CFUNC_constructor" been used instead of "JS_CFUNC_constructor_or_func" so it raises a constructor called without "new" issue. If I edit the wrap method and place JS_CFUNC_constructor_or_func that issue is gone and a this

proto = detail::GetPropertyPrototype(ctx, this_value);

Casts a trying to access undefined property issue. If I modify the previous code into

JSValue proto ;
if (JS_IsUndefined(this_value))
{
    proto = JS_GetClassProto(ctx, js_traits<std::shared_ptr<T>>::QJSClassId);
} else
    proto = detail::GetPropertyPrototype(ctx, this_value);

It works and

console.log(Point.emptyPoint instanceof GFX.Point)
console.log(Point.emptyPoint instanceof Point)

Both return TRUE, but when I do
console.log(Point.emptyPoint.x)

I get TypeError: Expected type struct Point, got object with classid 1, Im unsure what to edit at this point to support what we need, any help would be very appreciated.

commented

have you tried using ES6 for class inheritance? it works for me this way

eg:

class Point extends GFX.Point {
  constructor(x, y) {
    super(x, y);
  }

  ...
}