dop251 / goja

ECMAScript/JavaScript engine in pure Go

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Method calls in a class constructor fail to resolve under certain circumstances

matthewmueller opened this issue · comments

Hi @dop251, thanks so much on adding ES6 class support. It's enabled server-side rendering (SSR) in Svelte in pure Go!

I'm additionally working on running the Svelte compiler through Goja and I ran into an esoteric class bug. Here's a minimal reproduction script:

package main

import (
	"fmt"
	"os"

	"github.com/dop251/goja"
)

const code = `
class A {
  constructor(abc) {
    this.m()
    this.arr = []
    this.arr.forEach(fn => this.anything)
  }
  m() {
  }
}
new A()
`

func main() {
	if err := run(); err != nil {
		fmt.Fprintln(os.Stderr, err.Error())
		os.Exit(1)
	}
}

func run() error {
	prg, err := goja.Compile("main.js", code, false)
	if err != nil {
		return fmt.Errorf("unable to compile svelte compiler: %w", err)
	}
	vm := goja.New()
	_, err = vm.RunProgram(prg)
	if err != nil {
		return err
	}
	return nil
}

Running this, you should see TypeError: Cannot read property 'm' of undefined or null at main.js:4:5(3).

While the JS code itself works in V8:

class A {
  constructor(abc) {
    this.m()
    this.arr = []
    this.arr.forEach(fn => this.anything)
  }
  m() {
  }
}
new A()

This reproduction is fragile. Changing nearly anything will change the error, but you'll run into this issue while trying to evaluate the Svelte compiler:

https://github.com/sveltejs/svelte/blob/5a725713f7126e300928a0850a65cf18e50384a5/src/compiler/compile/Component.ts#L176-L189

TypeError: Object has no member 'walk_module_js' at compiler.js:23821:26(261)

Many thanks again for adding class support! I'm working on migrating from V8 to Goja for https://github.com/livebud/bud.