Skip to content

Commit

Permalink
add call class Constructor (#351)
Browse files Browse the repository at this point in the history
  • Loading branch information
buke authored Oct 8, 2024
1 parent e3bc34d commit be74e6c
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 1 deletion.
31 changes: 31 additions & 0 deletions quickjs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -854,3 +854,34 @@ func TestModule2(t *testing.T) {
require.NoError(t, err)
require.EqualValues(t, 144, ctx.Globals().Get("result").Int32())
}

func TestClassConstructor(t *testing.T) {
rt := quickjs.NewRuntime()
defer rt.Close()
ctx := rt.NewContext()
defer ctx.Close()

ret, err := ctx.Eval(`
class Foo {
x = 0;
constructor(x) {
this.x = x;
}
}
globalThis.Foo = Foo;
`)
defer ret.Free()
require.NoError(t, err)

Foo := ctx.Globals().Get("Foo")
defer Foo.Free()

fooInstance := Foo.New(ctx.Int32(10))
defer fooInstance.Free()

x := fooInstance.Get("x")
defer x.Free()

require.EqualValues(t, 10, x.Int32())

}
23 changes: 22 additions & 1 deletion value.go
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,27 @@ func (v Value) Call(fname string, args ...Value) Value {
return Value{ctx: v.ctx, ref: C.JS_Call(v.ctx.ref, fn.ref, v.ref, C.int(len(cargs)), &cargs[0])}
}

// Call Class Constructor
func (v Value) New(args ...Value) Value {
return v.CallConstructor(args...)
}

// Call calls the constructor with the given arguments.
func (v Value) CallConstructor(args ...Value) Value {
if !v.IsConstructor() {
return v.ctx.Error(errors.New("Object not a constructor"))
}

cargs := []C.JSValue{}
for _, x := range args {
cargs = append(cargs, x.ref)
}
if len(cargs) == 0 {
return Value{ctx: v.ctx, ref: C.JS_CallConstructor(v.ctx.ref, v.ref, C.int(0), nil)}
}
return Value{ctx: v.ctx, ref: C.JS_CallConstructor(v.ctx.ref, v.ref, C.int(len(cargs)), &cargs[0])}
}

// Error returns the error value of the value.
func (v Value) Error() error {
if !v.IsError() {
Expand Down Expand Up @@ -364,4 +385,4 @@ func (v Value) IsPromise() bool {
return false
}

// func (v Value) IsConstructor() bool { return C.JS_IsConstructor(v.ctx.ref, v.ref) == 1 }
func (v Value) IsConstructor() bool { return C.JS_IsConstructor(v.ctx.ref, v.ref) == 1 }

0 comments on commit be74e6c

Please sign in to comment.