J2V8 icon indicating copy to clipboard operation
J2V8 copied to clipboard

Need easy-to-use newInstance(type, args) like API in J2V8

Open JessHolle opened this issue 6 years ago • 3 comments

There appears to be no simple, easy way to invoke the JavaScript "new Xxx(arg1, arg2, ...)" from Java.

Am I missing something here?

Currently I'm introducing factory functions like "var newPromise = function(execFunction) { return new Promise(execFunction); };", but this is kind of awful.

JessHolle avatar Nov 05 '18 12:11 JessHolle

While I believe this is a significant gap, it is one a developer can fill for themselves if necessary via:

                V8Function newInstanceFunction = (V8Function) v8.executeObjectScript(
                        "(function() { return function(clazz) { return new clazz(...Array.prototype.slice.call(arguments, 1)); } })();",
                        MyV8Utils.class.getSimpleName() + "_java.js", 0);

and use thereof. This can all be wrapped up into a separate block of code that holds onto this instance for the given V8 instance and calls registerResource() so that it is automatically cleaned up.

Of course, even if this is the best possible implementation it would be best for J2V8 to do this and hide this mess from us.

JessHolle avatar Nov 20 '18 19:11 JessHolle

I was going to close this as a duplicate of https://github.com/eclipsesource/J2V8/issues/195 -- and did momentarily. However, https://github.com/eclipsesource/J2V8/issues/195 is essentially a question, whereas I am asserting a feature request here.

JessHolle avatar Nov 20 '18 19:11 JessHolle

We really need this feature. Currently we can't replicate the behavior of new because of the new.target property being probably undefined. Thus we just can't instantiate objects declared using ES6 classes other than by evaluating the instantiation.

icanwalkonwater avatar Jun 15 '19 09:06 icanwalkonwater