13. embind deriving from js 类的继承和JS

#include 
#include <string>

using namespace emscripten;

class Interface {
public:
    Interface() = default;
    // virtual std::string invoke(const std::string &str) = 0;
    virtual std::string invoke(const std::string &str) {
        return str + " - from 'C++'";
    }
};

// Glue between JavaScript and C/C++;
class DerivedClass : public wrapper {
public:
    EMSCRIPTEN_WRAPPER(DerivedClass);
    std::string invoke(const std::string &str) override {
        return callstring>("invoke", str);
    }
};

EMSCRIPTEN_BINDINGS(module) {
    class_("Interface")
        // .function("invoke", &Interface::invoke, pure_virtual())
        .function("invoke", optional_override([](Interface &self, const std::string &str){
            return self.Interface::invoke(str);
        }))
        // "extend" && "implement"
        .allow_subclass("DerivedClass");
}
__ATPOSTRUN__.push(() => {
    var DerivedClass = Module["Interface"].extend("Interface", {
    __construct: function() {
        this.__parent.__construct.call(this);
    },
    __destruct: function() {
        this.__parent.__destruct.call(this);
    },
    invoke: function(str) {
        return str + " - from 'YHSPY'";
    }
    });

    var instanceByExtend = new DerivedClass;
    console.log(instanceByExtend.invoke("Hello!"));

    // 
    var implementations = {
    invoke: function(str) {
          return str + " - from 'YHSPY'";
    }
    };
    var instanceByImpelment = Module["Interface"].implement(implementations);
    console.log(instanceByImpelment.invoke("Hello!"));
});

 

你可能感兴趣的:(13. embind deriving from js 类的继承和JS)