Browse Source

Added Runtime.New(). See #122

Dmitry Panov 5 years ago
parent
commit
a7d7d48272
2 changed files with 32 additions and 0 deletions
  1. 17 0
      runtime.go
  2. 15 0
      runtime_test.go

+ 17 - 0
runtime.go

@@ -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)
 

+ 15 - 0
runtime_test.go

@@ -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)