v8go
v8go copied to clipboard
Can't define method in constructor
import (
"github.com/sirupsen/logrus"
v8 "rogchap.com/v8go"
)
func main() {
iso := v8.NewIsolate()
global := v8.NewObjectTemplate(iso)
fn := v8.NewFunctionTemplate(iso, foo())
if err := global.Set("Foo", fn); err != nil {
logError(err)
}
ctx := v8.NewContext(iso, global)
defer recoverPanic(ctx)
jsVal, err := ctx.RunScript("new Foo()", "main.js")
if err != nil {
logError(err)
}
if jsVal.IsObject() {
logrus.Info("Returned object")
}
jsVal, err = ctx.RunScript("new Foo().a", "main2.js")// return "1"
if err != nil {
logError(err)
}
logResult(jsVal)
jsVal, err = ctx.RunScript("new Foo().hello()", "main3.js")// hello is undefined
if err != nil {
logError(err)
}
logResult(jsVal)
}
func foo() func(*v8.FunctionCallbackInfo) *v8.Value {
return func(info *v8.FunctionCallbackInfo) *v8.Value {
value, err := v8.NewValue(info.Context().Isolate(), "1")
if err != nil {
logError(err)
}
if err := info.This().Set("a", value); err != nil { //set property into "this"
logError(err)
}
fn := v8.NewFunctionTemplate(info.Context().Isolate(), helloFunc)
if err := info.This().Object().Set("hello", fn); err != nil { //v8go: unsupported object property type `*v8go.FunctionTemplate`
logError(err)
}
return nil
}
}
func helloFunc(info *v8.FunctionCallbackInfo) *v8.Value {
val, _ := v8.NewValue(info.Context().Isolate(), "hello")
return val
}
ERRO[0000] Fail JS execute - v8go: unsupported object property type `*v8go.FunctionTemplate`
INFO[0000] Returned object
ERRO[0000] Fail JS execute - v8go: unsupported object property type `*v8go.FunctionTemplate`
INFO[0000] JS result - 1
ERRO[0000] Fail JS execute - v8go: unsupported object property type `*v8go.FunctionTemplate`
ERRO[0000] Fail JS execute - TypeError: (intermediate value).hello is not a function
at main3.js:1:11
ERRO[0000] Panic occurred on function main.js - runtime error: invalid memory address or nil pointer dereference
You may be able to pass in the actual function from the function template with:
if err := info.This().Object().Set("hello", fn.GetFunction(info.Context())); err != nil {