dop251 / goja

ECMAScript/JavaScript engine in pure Go

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

There is a method defined to struct pointer, how to call it from struct elem?

garfeng opened this issue · comments

The go code is:

type Obj struct {
	Name string
}

func (o *Obj) RunInPtr() {
	fmt.Printf("[%s] run in ptr\r\n", o.Name)
}

func (o Obj) RunInElem() {
	fmt.Printf("[%s] run in elem\r\n", o.Name)
}

func newObjPtr(name string) *Obj {
	return &Obj{
		Name: name,
	}
}

func newObj(name string) Obj {
	return Obj{
		Name: name,
	}
}

func main() {
	engine := goja.New()
	engine.Set("newObj", newObj)
	engine.Set("newObjPtr", newObjPtr)

	buff, _ := ioutil.ReadFile(os.Args[1])
	code := string(buff)
	v, err := engine.RunScript(os.Args[1], code)
}

The test js is:

let a = newObjPtr("ptr");
a.RunInElem();
a.RunInPtr();

let b = newObj("elem");
b.RunInElem();
b.RunInPtr();

Then I get the error:

[ptr] run in elem
[ptr] run in ptr
[elem] run in elem
TypeError: Object has no member 'RunInPtr' at test.js:7:11(27)

PS:
I have wrote a tool to import go package to goja. https://github.com/garfeng/gojatools

The trouble is that, some function return the struct element instead of pointer of it.

Calling methods defined on it's pointer causes error.