Skip to content

Commit

Permalink
Added Runtime.New(). See dop251#122
Browse files Browse the repository at this point in the history
  • Loading branch information
dop251 committed Jan 26, 2020
1 parent 0a0a0d8 commit a7d7d48
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
17 changes: 17 additions & 0 deletions runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -1452,6 +1452,23 @@ func (r *Runtime) SetTimeSource(now Now) {
r.now = now
}

// New is an equivalent of the 'new' operator allowing to call it directly from Go.
func (r *Runtime) New(construct Value, args ...Value) (o *Object, err error) {
defer func() {
if x := recover(); x != nil {
switch x := x.(type) {
case *Exception:
err = x
case *InterruptedError:
err = x
default:
panic(x)
}
}
}()
return r.builtin_new(r.toObject(construct), args), nil
}

// Callable represents a JavaScript function that can be called from Go.
type Callable func(this Value, args ...Value) (Value, error)

Expand Down
15 changes: 15 additions & 0 deletions runtime_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1277,6 +1277,21 @@ func TestInf(t *testing.T) {
}
}

func TestRuntimeNew(t *testing.T) {
vm := New()
v, err := vm.New(vm.Get("Number"), vm.ToValue("12345"))
if err != nil {
t.Fatal(err)
}
if n, ok := v.Export().(int64); ok {
if n != 12345 {
t.Fatalf("n: %v", n)
}
} else {
t.Fatalf("v: %T", v)
}
}

/*
func TestArrayConcatSparse(t *testing.T) {
function foo(a,b,c)
Expand Down

0 comments on commit a7d7d48

Please sign in to comment.