On Wed, May 17, 2017 at 11:40 PM, Dan Goldstein <[email protected]> wrote:
> Hi friends,
>
>    I'm somewhat of a V8 novice and could use some help.  I have a JavaScript
> class, such as:
>
> class Animal
> {
>    constructor(numLegs)
>    {
>       this.numLegs = numLegs;
>    }
> }
>
>    Now, to create an instance of this class, I can easily run some
> JavaScript code, such as "var puppy = new Animal(4);"  However, I'd like to
> know how to create an instance of Animal and run its constructor from within
> C++, without running a script.
>
>    I've actually been able to accomplish this by calling object->Get() and
> passing in 'constructor' as the name of the function to retrieve.  Then I
> can call CallAsConstructor() and pass in arguments, and it does work.
> However, this is cumbersome, and the object I've created doesn't have a name
> -- e.g. there's no variable called puppy that I can reference in later
> JavaScript code.
>
>    My question is, is there a more elegant way to do this?  Or is this
> pretty much the right way to construct a JavaScript object from within C++?
>
> Thanks!
> Dan

If you don't want to execute JS code, Object::CallAsConstructor() or
Function::NewInstance() is the way to go.  You can set the result as a
property on the global object with
isolate->GetCurrentContext()->Global()->Set(...), that does the same
thing as `var puppy = ...`.

-- 
-- 
v8-users mailing list
[email protected]
http://groups.google.com/group/v8-users
--- 
You received this message because you are subscribed to the Google Groups 
"v8-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
For more options, visit https://groups.google.com/d/optout.

Reply via email to