How to return a new instance of class "V8" class V8 from C ++?

When using V8 as a scripting engine, I open a C ++ function called construct_with_ec6_syntaxfor Javascript. When called, this function should simply return an instance some_ec6_class.

This C ++ function should basically do the following equivalent Javascript:

return new some_ec6_class(111, 222);

This class will be defined in Javascript as follows with EC6 syntax:

class some_ec6_class
{
    constructor(x, y) {
        this.result = x + y;
    }
}

My goal is to run the following in Javascript ...

var the_instance = construct_with_ec6_syntax(111, 222);
the_instance.result ; // .. and get 333 here.

My current implementation for the C ++ function is as follows:

void construct_with_ec6_syntax(const FunctionCallbackInfo<Value>& args) {
    Handle<Object> global = args.GetIsolate()->GetCurrentContext()->Global();
    std::string newvecfunc = "some_ec6_class";
    Handle<Value> value = global->Get(String::NewFromUtf8(args.GetIsolate(), newvecfunc.c_str(), String::kNormalString, newvecfunc.length()));
    Local<Value> result;
    if (value->IsFunction()) {
        Handle<Function> func = Handle<Function>::Cast(value);
        Handle<Value> args2[2];
        args2[0] = Number::New(args.GetIsolate(), 111);
        args2[1] = Number::New(args.GetIsolate(), 222);
        result = func->CallAsConstructor(args.GetIsolate()->GetCurrentContext(), 2, args2).ToLocalChecked();
    }   
    args.GetReturnValue().Set(result);
}   

Javascript undefined! , . xaxxon, , value->IsFunction() false, value->IsUndefined() true. , EC6, .

function some_non_ec6_class(x, y) // this guy would work with the above function
{
    this.result = x + y;
}

! - , , constructor , CallAsConstructor?

!

( javascript v8 ++ , .)

V8 checkout 22 2016 . :

https://gist.github.com/rayburgemeestre/c0abd528f6f67edbfe686d484c45ddbb

:

, "" : https://gist.github.com/rayburgemeestre/df6193d532c7b7908fe27c89799bfa3a

v8-: https://groups.google.com/forum/#!topic/v8-users/Hj2j4rJMwBw

+4
1

class - javascript, let. , class, ( , let). context.global, :

http://exploringjs.com/es6/ch_variables.html

function    Complete    Block   Yes

class       No          Block   No

:

some_es6_class = class{}; 

++ " es6":

class some_es6_class{};
some_native_function(some_es6_class);

: , , LexicalEnvironment, script, . , LexicalEnvironments, . API (, , ), , JS , ).

+2

Source: https://habr.com/ru/post/1664099/


All Articles