在c++中继承JavaScript函数

Inheriting from JavaScript function in C++

本文关键字:JavaScript 函数 继承 c++      更新时间:2023-10-16

我有一个下面的JavaScript基本函数:

function Animal { }  
Animal.prototype.move = function () { 
  //... 
}

我也有一个派生的JavaScript函数,像这样:

function Dog {
  Dog.super_.call(this);
}
util.inherits(Dog, Animal);
Dog.prototype.bark = function () {
  // ...
}

现在我想创建一个c++插件,它与派生的插件完全相同Dog JavaScript函数

void Dog::Init(Handle<Object> exports, Handle<Object> module) {
  Isolate* isolate = Isolate::GetCurrent();
  Local<Function> require = Local<Function>::Cast(module->Get(
    String::NewFromUtf8(isolate, "require")));
  Local<Value> args[] = {
    String::NewFromUtf8(isolate, "./animal")
  };  
  Local<Value> animalModule = require->Call(module, 1, args);
  Local<Function> animalFunc = Local<Function>::Cast(animalModule);   
  Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);
  // tpl->Inherit(animalFunc); // <-- HERE
  tpl->SetClassName(String::NewFromUtf8(isolate, "Dog"));
  tpl->InstanceTemplate()->SetInternalFieldCount(1);  
  NODE_SET_PROTOTYPE_METHOD(tpl, "bark", Bark);
  constructor.Reset(isolate, tpl->GetFunction());
  exports->Set(String::NewFromUtf8(isolate, "Dog"),
    tpl->GetFunction());    
}

我如何从animalFunc/animalModule获得FunctionTemplate,以便能够在tpl函数模板中继承它?或者我应该赋值animalFunc。Prototype tpl.prototype

唉,你不能。

查看此讨论:https://github.com/nodejs/node-addon-api/issues/229

这就是为什么在c++中没有继承JS类的标准方法的主要原因。