Browse Source

Added Runtime.CreateObject(). See #45

Dmitry Panov 8 years ago
parent
commit
507e36ce7a
2 changed files with 34 additions and 0 deletions
  1. 5 0
      runtime.go
  2. 29 0
      runtime_test.go

+ 5 - 0
runtime.go

@@ -315,6 +315,11 @@ func (r *Runtime) NewObject() (v *Object) {
 	return r.newBaseObject(r.global.ObjectPrototype, classObject).val
 }
 
+// CreateObject creates an object with given prototype. Equivalent of Object.create(proto).
+func (r *Runtime) CreateObject(proto *Object) *Object {
+	return r.newBaseObject(proto, classObject).val
+}
+
 func (r *Runtime) NewTypeError(args ...interface{}) *Object {
 	msg := ""
 	if len(args) > 0 {

+ 29 - 0
runtime_test.go

@@ -972,6 +972,35 @@ func TestNativeConstruct(t *testing.T) {
 	}
 }
 
+func TestCreateObject(t *testing.T) {
+	const SCRIPT = `
+	inst instanceof C;
+	`
+
+	r := New()
+	c := r.ToValue(func(call ConstructorCall) *Object {
+		return nil
+	})
+
+	proto := c.(*Object).Get("prototype").(*Object)
+
+	inst := r.CreateObject(proto)
+
+	r.Set("C", c)
+	r.Set("inst", inst)
+
+	prg := MustCompile("test.js", SCRIPT, false)
+
+	res, err := r.RunProgram(prg)
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	if !res.StrictEquals(valueTrue) {
+		t.Fatalf("Unexpected result: %v", res)
+	}
+}
+
 /*
 func TestArrayConcatSparse(t *testing.T) {
 function foo(a,b,c)