quickjs

package module
v0.5.7 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 17, 2025 License: MIT Imports: 16 Imported by: 22

README

quickjs-go

English | 简体中文

Test codecov Go Report Card GoDoc FOSSA Status

Go bindings to QuickJS: a fast, small, and embeddable ES2020 JavaScript interpreter.

Platform Support

we prebuilt quickjs static library for the following platforms:

Platform Arch Static Library
Linux x64 libquickjs.a
Linux arm64 libquickjs.a
Windows x64 libquickjs.a
Windows x86 libquickjs.a
MacOS x64 libquickjs.a
MacOS arm64 libquickjs.a

* for build on windows, ples see: https://github.com/buke/quickjs-go/issues/151#issuecomment-2134307728

Version Notes

quickjs-go QuickJS
v0.5.x v2025-04-26
v0.4.x v2024-02-14
v0.3.x v2024-01-13
v0.2.x v2023-12-09
v0.1.x v2021-03-27

Features

  • Evaluate script
  • Compile script into bytecode and Eval from bytecode
  • Operate JavaScript values and objects in Go
  • Bind Go function to JavaScript async/sync function
  • Simple exception throwing and catching
  • Marshal/Unmarshal Go values to/from JavaScript values
  • Full TypedArray support (Int8Array, Uint8Array, Float32Array, etc.)
  • Class Binding with manual and automatic reflection-based approaches

Guidelines

  1. Free quickjs.Runtime and quickjs.Context once you are done using them.
  2. Free quickjs.Value's returned by Eval() and EvalFile(). All other values do not need to be freed, as they get garbage-collected.
  3. Use ctx.Loop() wait for promise/job result after you using promise/job
  4. You may access the stacktrace of an error returned by Eval() or EvalFile() by casting it to a *quickjs.Error.
  5. Make new copies of arguments should you want to return them in functions you created.

Usage

import "github.com/buke/quickjs-go"
Run a script
package main

import (
    "fmt"

    "github.com/buke/quickjs-go"
)

func main() {
    // Create a new runtime
    rt := quickjs.NewRuntime()
    defer rt.Close()

    // Create a new context
    ctx := rt.NewContext()
    defer ctx.Close()

    ret, err := ctx.Eval("'Hello ' + 'QuickJS!'")
    if err != nil {
        println(err.Error())
    }
    fmt.Println(ret.String())
}
Get/Set Javascript Object
package main

import (
    "fmt"

    "github.com/buke/quickjs-go"
)

func main() {
    // Create a new runtime
    rt := quickjs.NewRuntime()
    defer rt.Close()

    // Create a new context
    ctx := rt.NewContext()
    defer ctx.Close()

    test := ctx.Object()
    test.Set("A", ctx.String("String A"))
    test.Set("B", ctx.String("String B"))
    test.Set("C", ctx.String("String C"))
    ctx.Globals().Set("test", test)

    ret, _ := ctx.Eval(`Object.keys(test).map(key => test[key]).join(" ")`)
    defer ret.Free()
    fmt.Println(ret.String())
}

Bind Go Funtion to Javascript async/sync function
package main
import "github.com/buke/quickjs-go"

func main() {
    // Create a new runtime
    rt := quickjs.NewRuntime()
    defer rt.Close()

    // Create a new context
    ctx := rt.NewContext()
    defer ctx.Close()

    // Create a new object
    test := ctx.Object()
    defer test.Free()
    // bind properties to the object
    test.Set("A", test.Context().String("String A"))
    test.Set("B", ctx.Int32(0))
    test.Set("C", ctx.Bool(false))
    // bind go function to js object
    test.Set("hello", ctx.Function(func(ctx *quickjs.Context, this quickjs.Value, args []quickjs.Value) quickjs.Value {
        return ctx.String("Hello " + args[0].String())
    }))

    // bind "test" object to global object
    ctx.Globals().Set("test", test)

    // call js function by js
    js_ret, _ := ctx.Eval(`test.hello("Javascript!")`)
    fmt.Println(js_ret.String())

    // call js function by go
    go_ret := ctx.Globals().Get("test").Call("hello", ctx.String("Golang!"))
    fmt.Println(go_ret.String())

    // bind go function to Javascript async function using Function + Promise
    ctx.Globals().Set("testAsync", ctx.Function(func(ctx *quickjs.Context, this quickjs.Value, args []quickjs.Value) quickjs.Value {
        return ctx.Promise(func(resolve, reject func(quickjs.Value)) {
            resolve(ctx.String("Hello Async Function!"))
        })
    }))

    ret, _ := ctx.Eval(`
            var ret;
            testAsync().then(v => ret = v)
        `)
    defer ret.Free()

    // wait for promise resolve
    ctx.Loop()

    //get promise result
    asyncRet, _ := ctx.Eval("ret")
    defer asyncRet.Free()

    fmt.Println(asyncRet.String())

    // Output:
    // Hello Javascript!
    // Hello Golang!
    // Hello Async Function!
}
Error Handling
package main

import (
    "fmt"

    "github.com/buke/quickjs-go"
)

func main() {
    // Create a new runtime
    rt := quickjs.NewRuntime()
    defer rt.Close()

    // Create a new context
    ctx := rt.NewContext()
    defer ctx.Close()

    ctx.Globals().SetFunction("A", func(ctx *Context, this Value, args []Value) Value {
        // raise error
        return ctx.ThrowError(expected)
    })

    _, actual := ctx.Eval("A()")
    fmt.Println(actual.Error())
}
TypedArray Support

QuickJS-Go provides full support for JavaScript TypedArrays, enabling efficient binary data processing between Go and JavaScript.

Creating TypedArrays from Go
package main

import (
    "fmt"
    "github.com/buke/quickjs-go"
)

func main() {
    rt := quickjs.NewRuntime()
    defer rt.Close()
    ctx := rt.NewContext()
    defer ctx.Close()

    // Create various TypedArrays from Go slices
    int8Data := []int8{-128, -1, 0, 1, 127}
    int8Array := ctx.Int8Array(int8Data)
    defer int8Array.Free()

    uint8Data := []uint8{0, 128, 255}
    uint8Array := ctx.Uint8Array(uint8Data)
    defer uint8Array.Free()

    float32Data := []float32{-3.14, 0.0, 2.718, 100.5}
    float32Array := ctx.Float32Array(float32Data)
    defer float32Array.Free()

    int64Data := []int64{-9223372036854775808, 0, 9223372036854775807}
    bigInt64Array := ctx.BigInt64Array(int64Data)
    defer bigInt64Array.Free()

    // Set TypedArrays as global variables
    ctx.Globals().Set("int8Array", int8Array)
    ctx.Globals().Set("uint8Array", uint8Array)
    ctx.Globals().Set("float32Array", float32Array)
    ctx.Globals().Set("bigInt64Array", bigInt64Array)

    // Use in JavaScript
    result, _ := ctx.Eval(`
        // Check types
        const results = {
            int8Type: int8Array instanceof Int8Array,
            uint8Type: uint8Array instanceof Uint8Array,
            float32Type: float32Array instanceof Float32Array,
            bigInt64Type: bigInt64Array instanceof BigInt64Array,
            // Calculate sum of float32 array
            float32Sum: float32Array.reduce((sum, val) => sum + val, 0)
        };
        results;
    `)
    defer result.Free()

    fmt.Println("Results:", result.JSONStringify())
}
Converting JavaScript TypedArrays to Go
package main

import (
    "fmt"
    "github.com/buke/quickjs-go"
)

func main() {
    rt := quickjs.NewRuntime()
    defer rt.Close()
    ctx := rt.NewContext()
    defer ctx.Close()

    // Create TypedArrays in JavaScript
    jsTypedArrays, _ := ctx.Eval(`
        ({
            int8: new Int8Array([-128, -1, 0, 1, 127]),
            uint16: new Uint16Array([0, 32768, 65535]),
            float64: new Float64Array([Math.PI, Math.E, 42.5]),
            bigUint64: new BigUint64Array([0n, 18446744073709551615n])
        })
    `)
    defer jsTypedArrays.Free()

    // Convert to Go slices
    int8Array := jsTypedArrays.Get("int8")
    defer int8Array.Free()
    if int8Array.IsInt8Array() {
        goInt8Slice, err := int8Array.ToInt8Array()
        if err == nil {
            fmt.Printf("Int8Array: %v\n", goInt8Slice)
        }
    }

    uint16Array := jsTypedArrays.Get("uint16")
    defer uint16Array.Free()
    if uint16Array.IsUint16Array() {
        goUint16Slice, err := uint16Array.ToUint16Array()
        if err == nil {
            fmt.Printf("Uint16Array: %v\n", goUint16Slice)
        }
    }

    float64Array := jsTypedArrays.Get("float64")
    defer float64Array.Free()
    if float64Array.IsFloat64Array() {
        goFloat64Slice, err := float64Array.ToFloat64Array()
        if err == nil {
            fmt.Printf("Float64Array: %v\n", goFloat64Slice)
        }
    }

    bigUint64Array := jsTypedArrays.Get("bigUint64")
    defer bigUint64Array.Free()
    if bigUint64Array.IsBigUint64Array() {
        goBigUint64Slice, err := bigUint64Array.ToBigUint64Array()
        if err == nil {
            fmt.Printf("BigUint64Array: %v\n", goBigUint64Slice)
        }
    }
}
TypedArray Types Support
Go Type JavaScript TypedArray Context Method Value Method
[]int8 Int8Array ctx.Int8Array() val.ToInt8Array()
[]uint8 Uint8Array ctx.Uint8Array() val.ToUint8Array()
[]uint8 Uint8ClampedArray ctx.Uint8ClampedArray() val.ToUint8Array()
[]int16 Int16Array ctx.Int16Array() val.ToInt16Array()
[]uint16 Uint16Array ctx.Uint16Array() val.ToUint16Array()
[]int32 Int32Array ctx.Int32Array() val.ToInt32Array()
[]uint32 Uint32Array ctx.Uint32Array() val.ToUint32Array()
[]float32 Float32Array ctx.Float32Array() val.ToFloat32Array()
[]float64 Float64Array ctx.Float64Array() val.ToFloat64Array()
[]int64 BigInt64Array ctx.BigInt64Array() val.ToBigInt64Array()
[]uint64 BigUint64Array ctx.BigUint64Array() val.ToBigUint64Array()
[]byte ArrayBuffer ctx.ArrayBuffer() val.ToByteArray()
TypedArray Detection
package main

import (
    "fmt"
    "github.com/buke/quickjs-go"
)

func main() {
    rt := quickjs.NewRuntime()
    defer rt.Close()
    ctx := rt.NewContext()
    defer ctx.Close()

    // Create various arrays
    regularArray, _ := ctx.Eval(`[1, 2, 3]`)
    defer regularArray.Free()

    int32Array := ctx.Int32Array([]int32{1, 2, 3})
    defer int32Array.Free()

    float64Array := ctx.Float64Array([]float64{1.1, 2.2, 3.3})
    defer float64Array.Free()

    // Detect array types
    fmt.Printf("Regular array IsArray: %v\n", regularArray.IsArray())
    fmt.Printf("Regular array IsTypedArray: %v\n", regularArray.IsTypedArray())

    fmt.Printf("Int32Array IsTypedArray: %v\n", int32Array.IsTypedArray())
    fmt.Printf("Int32Array IsInt32Array: %v\n", int32Array.IsInt32Array())
    fmt.Printf("Int32Array IsFloat64Array: %v\n", int32Array.IsFloat64Array())

    fmt.Printf("Float64Array IsTypedArray: %v\n", float64Array.IsTypedArray())
    fmt.Printf("Float64Array IsFloat64Array: %v\n", float64Array.IsFloat64Array())
    fmt.Printf("Float64Array IsInt32Array: %v\n", float64Array.IsInt32Array())
}
Binary Data Processing Example
package main

import (
    "fmt"
    "github.com/buke/quickjs-go"
)

func main() {
    rt := quickjs.NewRuntime()
    defer rt.Close()
    ctx := rt.NewContext()
    defer ctx.Close()

    // Process image-like data (simulate RGB pixels)
    imageData := []uint8{
        255, 0, 0,    // Red pixel
        0, 255, 0,    // Green pixel  
        0, 0, 255,    // Blue pixel
        255, 255, 0,  // Yellow pixel
    }

    // Send to JavaScript as Uint8Array
    imageArray := ctx.Uint8Array(imageData)
    ctx.Globals().Set("imageData", imageArray)

    // Process in JavaScript
    result, _ := ctx.Eval(`
        // Convert RGB to grayscale
        const grayscale = new Uint8Array(imageData.length / 3);
        for (let i = 0; i < imageData.length; i += 3) {
            const r = imageData[i];
            const g = imageData[i + 1];
            const b = imageData[i + 2];
            grayscale[i / 3] = Math.round(0.299 * r + 0.587 * g + 0.114 * b);
        }
        grayscale;
    `)
    defer result.Free()

    // Convert back to Go
    if result.IsUint8Array() {
        grayscaleData, err := result.ToUint8Array()
        if err == nil {
            fmt.Printf("Original RGB: %v\n", imageData)
            fmt.Printf("Grayscale: %v\n", grayscaleData)
        }
    }
}
Marshal/Unmarshal Go Values

QuickJS-Go provides seamless conversion between Go and JavaScript values through the Marshal and Unmarshal methods.

Basic Types
package main

import (
    "fmt"
    "github.com/buke/quickjs-go"
)

func main() {
    rt := quickjs.NewRuntime()
    defer rt.Close()
    ctx := rt.NewContext()
    defer ctx.Close()

    // Marshal Go values to JavaScript
    data := map[string]interface{}{
        "name":    "John Doe",
        "age":     30,
        "active":  true,
        "scores":  []int{85, 92, 78},
        "address": map[string]string{
            "city":    "New York",
            "country": "USA",
        },
        // TypedArray will be automatically created for typed slices
        "floatData": []float32{1.1, 2.2, 3.3},
        "intData":   []int32{100, 200, 300},
        "byteData":  []byte{0x48, 0x65, 0x6C, 0x6C, 0x6F}, // "Hello" in bytes
    }

    jsVal, err := ctx.Marshal(data)
    if err != nil {
        panic(err)
    }
    defer jsVal.Free()

    // Use the marshaled value in JavaScript
    ctx.Globals().Set("user", jsVal)
    result, _ := ctx.Eval(`
        const info = user.name + " is " + user.age + " years old";
        const floatArrayType = user.floatData instanceof Float32Array;
        const intArrayType = user.intData instanceof Int32Array;
        const byteArrayType = user.byteData instanceof ArrayBuffer;
        
        ({
            info: info,
            floatArrayType: floatArrayType,
            intArrayType: intArrayType,
            byteArrayType: byteArrayType,
            byteString: new TextDecoder().decode(user.byteData)
        });
    `)
    defer result.Free()
    fmt.Println("Result:", result.JSONStringify())

    // Unmarshal JavaScript values back to Go
    var userData map[string]interface{}
    err = ctx.Unmarshal(jsVal, &userData)
    if err != nil {
        panic(err)
    }
    fmt.Printf("Unmarshaled: %+v\n", userData)
}
Struct Marshaling with Tags
package main

import (
    "fmt"
    "time"
    "github.com/buke/quickjs-go"
)

type User struct {
    ID        int64     `js:"id"`
    Name      string    `js:"name"`
    Email     string    `json:"email_address"`
    CreatedAt time.Time `js:"created_at"`
    IsActive  bool      `js:"is_active"`
    Tags      []string  `js:"tags"`
    // TypedArray fields
    Scores    []float32 `js:"scores"`    // Will become Float32Array
    Data      []int32   `js:"data"`      // Will become Int32Array
    Binary    []byte    `js:"binary"`    // Will become ArrayBuffer
    // unexported fields are ignored
    password  string
    // Fields with "-" tag are skipped
    Secret    string `js:"-"`
}

func main() {
    rt := quickjs.NewRuntime()
    defer rt.Close()
    ctx := rt.NewContext()
    defer ctx.Close()

    user := User{
        ID:        123,
        Name:      "Alice",
        Email:     "alice@example.com",
        CreatedAt: time.Now(),
        IsActive:  true,
        Tags:      []string{"admin", "user"},
        Scores:    []float32{95.5, 87.2, 92.0},
        Data:      []int32{1000, 2000, 3000},
        Binary:    []byte{0x41, 0x42, 0x43}, // "ABC"
        password:  "secret123",
        Secret:    "top-secret",
    }

    // Marshal struct to JavaScript
    jsVal, err := ctx.Marshal(user)
    if err != nil {
        panic(err)
    }
    defer jsVal.Free()

    // Check TypedArray types in JavaScript
    ctx.Globals().Set("user", jsVal)
    result, _ := ctx.Eval(`
        ({
            scoresType: user.scores instanceof Float32Array,
            dataType: user.data instanceof Int32Array,
            binaryType: user.binary instanceof ArrayBuffer,
            binaryString: new TextDecoder().decode(user.binary),
            avgScore: user.scores.reduce((sum, score) => sum + score) / user.scores.length
        });
    `)
    defer result.Free()
    fmt.Println("TypedArray info:", result.JSONStringify())

    // Modify in JavaScript
    modifyResult, _ := ctx.Eval(`
        user.name = "Alice Smith";
        user.tags.push("moderator");
        // Modify TypedArray data
        user.scores[0] = 98.5;
        user;
    `)
    defer modifyResult.Free()

    // Unmarshal back to Go struct
    var updatedUser User
    err = ctx.Unmarshal(modifyResult, &updatedUser)
    if err != nil {
        panic(err)
    }

    fmt.Printf("Updated user: %+v\n", updatedUser)
    // Note: password and Secret fields remain unchanged (not serialized)
}
Custom Marshal/Unmarshal
package main

import (
    "fmt"
    "strings"
    "github.com/buke/quickjs-go"
)

type CustomType struct {
    Value string
}

// Implement Marshaler interface
func (c CustomType) MarshalJS(ctx *quickjs.Context) (quickjs.Value, error) {
    return ctx.String("custom:" + c.Value), nil
}

// Implement Unmarshaler interface
func (c *CustomType) UnmarshalJS(ctx *quickjs.Context, val quickjs.Value) error {
    if val.IsString() {
        str := val.ToString()
        if strings.HasPrefix(str, "custom:") {
            c.Value = str[7:] // Remove "custom:" prefix
        } else {
            c.Value = str
        }
    }
    return nil
}

func main() {
    rt := quickjs.NewRuntime()
    defer rt.Close()
    ctx := rt.NewContext()
    defer ctx.Close()

    // Marshal custom type
    custom := CustomType{Value: "hello"}
    jsVal, err := ctx.Marshal(custom)
    if err != nil {
        panic(err)
    }
    defer jsVal.Free()

    fmt.Println("Marshaled:", jsVal.String()) // Output: custom:hello

    // Unmarshal back
    var result CustomType
    err = ctx.Unmarshal(jsVal, &result)
    if err != nil {
        panic(err)
    }
    fmt.Printf("Unmarshaled: %+v\n", result) // Output: {Value:hello}
}
Type Mappings

Go to JavaScript:

  • bool → JavaScript boolean
  • int, int8, int16, int32 → JavaScript number (32-bit)
  • int64 → JavaScript number (64-bit)
  • uint, uint8, uint16, uint32 → JavaScript number (32-bit unsigned)
  • uint64 → JavaScript BigInt
  • float32, float64 → JavaScript number
  • string → JavaScript string
  • []byte → JavaScript ArrayBuffer
  • []int8 → JavaScript Int8Array
  • []uint8 → JavaScript Uint8Array
  • []int16 → JavaScript Int16Array
  • []uint16 → JavaScript Uint16Array
  • []int32 → JavaScript Int32Array
  • []uint32 → JavaScript Uint32Array
  • []float32 → JavaScript Float32Array
  • []float64 → JavaScript Float64Array
  • []int64 → JavaScript BigInt64Array
  • []uint64 → JavaScript BigUint64Array
  • slice/array → JavaScript Array (for non-typed arrays)
  • map → JavaScript Object
  • struct → JavaScript Object
  • pointer → recursively marshal pointed value (nil becomes null)

JavaScript to Go:

  • JavaScript null/undefined → Go nil pointer or zero value
  • JavaScript boolean → Go bool
  • JavaScript number → Go numeric types (with appropriate conversion)
  • JavaScript BigInt → Go uint64/int64/*big.Int
  • JavaScript string → Go string
  • JavaScript Array → Go slice/array
  • JavaScript Object → Go map/struct
  • JavaScript ArrayBuffer → Go []byte
  • JavaScript Int8Array → Go []int8
  • JavaScript Uint8Array/Uint8ClampedArray → Go []uint8
  • JavaScript Int16Array → Go []int16
  • JavaScript Uint16Array → Go []uint16
  • JavaScript Int32Array → Go []int32
  • JavaScript Uint32Array → Go []uint32
  • JavaScript Float32Array → Go []float32
  • JavaScript Float64Array → Go []float64
  • JavaScript BigInt64Array → Go []int64
  • JavaScript BigUint64Array → Go []uint64

When unmarshaling into interface{}, the following types are used:

  • nil for null/undefined
  • bool for boolean
  • int64 for integer numbers
  • float64 for floating-point numbers
  • string for string
  • []interface{} for Array
  • map[string]interface{} for Object
  • *big.Int for BigInt
  • []byte for ArrayBuffer
Class Binding

QuickJS-Go provides powerful class binding capabilities that allow you to seamlessly bridge Go structs to JavaScript classes with automatic memory management and inheritance support.

Manual Class Binding

Create JavaScript classes manually with full control over methods, properties, and accessors:

package main

import (
    "fmt"
    "math"
    "github.com/buke/quickjs-go"
)

type Point struct {
    X, Y float64
    Name string
}

func (p *Point) Distance() float64 {
    return math.Sqrt(p.X*p.X + p.Y*p.Y)
}

func (p *Point) Move(dx, dy float64) {
    p.X += dx
    p.Y += dy
}

func main() {
    rt := quickjs.NewRuntime()
    defer rt.Close()
    ctx := rt.NewContext()
    defer ctx.Close()

    // Create Point class using ClassBuilder
    pointConstructor, _, err := quickjs.NewClassBuilder("Point").
        Constructor(func(ctx *quickjs.Context, instance quickjs.Value, args []quickjs.Value) (interface{}, error) {
            x, y := 0.0, 0.0
            name := "Unnamed Point"
            
            if len(args) > 0 { x = args[0].Float64() }
            if len(args) > 1 { y = args[1].Float64() }
            if len(args) > 2 { name = args[2].String() }
            
            // Return Go object for automatic association
            return &Point{X: x, Y: y, Name: name}, nil
        }).
        // Accessors provide getter/setter functionality with custom logic
        Accessor("x", 
            func(ctx *quickjs.Context, this quickjs.Value) quickjs.Value {
                point, _ := this.GetGoObject()
                return ctx.Float64(point.(*Point).X)
            },
            func(ctx *quickjs.Context, this quickjs.Value, value quickjs.Value) quickjs.Value {
                point, _ := this.GetGoObject()
                point.(*Point).X = value.Float64()
                return ctx.Undefined()
            }).
        Accessor("y",
            func(ctx *quickjs.Context, this quickjs.Value) quickjs.Value {
                point, _ := this.GetGoObject()
                return ctx.Float64(point.(*Point).Y)
            },
            func(ctx *quickjs.Context, this quickjs.Value, value quickjs.Value) quickjs.Value {
                point, _ := this.GetGoObject()
                point.(*Point).Y = value.Float64()
                return ctx.Undefined()
            }).
        // Properties are bound directly to each instance (faster for static values)
        Property("version", ctx.String("1.0.0")).
        Property("type", ctx.String("Point")).
        // Read-only property
        Property("readOnly", ctx.Bool(true), quickjs.PropertyConfigurable).
        // Instance methods
        Method("distance", func(ctx *quickjs.Context, this quickjs.Value, args []quickjs.Value) quickjs.Value {
            point, _ := this.GetGoObject()
            return ctx.Float64(point.(*Point).Distance())
        }).
        Method("move", func(ctx *quickjs.Context, this quickjs.Value, args []quickjs.Value) quickjs.Value {
            point, _ := this.GetGoObject()
            dx, dy := 0.0, 0.0
            if len(args) > 0 { dx = args[0].Float64() }
            if len(args) > 1 { dy = args[1].Float64() }
            point.(*Point).Move(dx, dy)
            return ctx.Undefined()
        }).
        Method("getName", func(ctx *quickjs.Context, this quickjs.Value, args []quickjs.Value) quickjs.Value {
            point, _ := this.GetGoObject()
            return ctx.String(point.(*Point).Name)
        }).
        // Static method
        StaticMethod("origin", func(ctx *quickjs.Context, this quickjs.Value, args []quickjs.Value) quickjs.Value {
            // Create a new Point at origin
            origin := &Point{X: 0, Y: 0, Name: "Origin"}
            jsVal, _ := ctx.Marshal(origin)
            return jsVal
        }).
        Build(ctx)

    if err != nil {
        panic(err)
    }

    // Register the class
    ctx.Globals().Set("Point", pointConstructor)

    // Use in JavaScript
    result, _ := ctx.Eval(`
        const p = new Point(3, 4, "My Point");
        const dist1 = p.distance();
        p.move(1, 1);
        const dist2 = p.distance();
        
        // Static method usage
        const origin = Point.origin();
        
        ({ 
            // Accessor usage
            x: p.x,
            y: p.y,
            // Property usage
            version: p.version,
            type: p.type,
            readOnly: p.readOnly,
            hasOwnProperty: p.hasOwnProperty('version'), // true for properties
            // Method results
            name: p.getName(),
            initialDistance: dist1,
            finalDistance: dist2,
            // Static method result
            originDistance: Math.sqrt(origin.x * origin.x + origin.y * origin.y)
        });
    `)
    defer result.Free()
    
    fmt.Println("Result:", result.JSONStringify())
    
    // Demonstrate the difference between accessors and properties
    propertyTest, _ := ctx.Eval(`
        const p1 = new Point(1, 1);
        const p2 = new Point(2, 2);
        
        // Properties are instance-specific values
        const sameVersion = p1.version === p2.version; // true, same static value
        
        // Accessors provide dynamic values from Go object
        const differentX = p1.x !== p2.x; // true, different values from Go objects
        
        ({ sameVersion, differentX });
    `)
    defer propertyTest.Free()
    
    fmt.Println("Property vs Accessor:", propertyTest.JSONStringify())
}
Automatic Class Binding with Reflection

Automatically generate JavaScript classes from Go structs using reflection. Important: Go struct fields are automatically converted to JavaScript class accessors, providing getter/setter functionality that directly maps to the underlying Go object fields, ensuring automatic synchronization between JavaScript and Go.

package main

import (
    "fmt"
    "github.com/buke/quickjs-go"
)

type User struct {
    ID        int64     `js:"id"`           // Becomes accessor: user.id
    Name      string    `js:"name"`         // Becomes accessor: user.name
    Email     string    `json:"email_address"` // Becomes accessor: user.email_address
    Age       int       `js:"age"`          // Becomes accessor: user.age
    IsActive  bool      `js:"is_active"`    // Becomes accessor: user.is_active
    Scores    []float32 `js:"scores"`       // Becomes accessor: user.scores (Float32Array)
    private   string    // Not accessible (unexported)
    Secret    string    `js:"-"`            // Explicitly ignored
}

func (u *User) GetFullInfo() string {
    return fmt.Sprintf("%s (%s) - Age: %d", u.Name, u.Email, u.Age)
}

func (u *User) UpdateEmail(newEmail string) {
    u.Email = newEmail
}

func (u *User) AddScore(score float32) {
    u.Scores = append(u.Scores, score)
}

func main() {
    rt := quickjs.NewRuntime()
    defer rt.Close()
    ctx := rt.NewContext()
    defer ctx.Close()

    // Automatically create User class from struct
    userConstructor, _, err := ctx.BindClass(&User{})
    if err != nil {
        panic(err)
    }

    ctx.Globals().Set("User", userConstructor)

    // Use with positional arguments
    result1, _ := ctx.Eval(`
        const user1 = new User(1, "Alice", "alice@example.com", 25, true, [95.5, 87.2]);
        user1.GetFullInfo();
    `)
    defer result1.Free()
    fmt.Println("Positional:", result1.String())

    // Use with named arguments (object parameter)
    result2, _ := ctx.Eval(`
        const user2 = new User({
            id: 2,
            name: "Bob",
            email_address: "bob@example.com",
            age: 30,
            is_active: true,
            scores: [88.0, 92.5, 85.0]
        });
        
        // Call methods
        user2.UpdateEmail("bob.smith@example.com");
        user2.AddScore(95.0);
        
        // Access fields via accessors (directly map to Go struct fields)
        user2.age = 31;        // Setter: modifies the Go struct field
        const newAge = user2.age; // Getter: reads from the Go struct field
        
        ({
            info: user2.GetFullInfo(),
            email: user2.email_address,  // Accessor getter
            age: newAge,                 // Modified via accessor setter
            scoresType: user2.scores instanceof Float32Array,
            scoresLength: user2.scores.length
        });
    `)
    defer result2.Free()
    fmt.Println("Named:", result2.JSONStringify())

    // Demonstrate field accessor automatic synchronization
    result3, _ := ctx.Eval(`
        const user3 = new User(3, "Charlie", "charlie@example.com", 35, true, []);
        
        // Field accessors provide direct access to Go struct fields with automatic sync
        const originalName = user3.name;  // Getter: reads Go struct field
        
        user3.name = "Charles";           // Setter: modifies Go struct field immediately
        const newName = user3.name;       // Getter: reads modified field
        
        // Changes are automatically synchronized with Go object
        const info = user3.GetFullInfo(); // Method sees the changed name immediately
        
        // Verify synchronization by changing multiple fields
        user3.age = 36;
        user3.email_address = "charles.updated@example.com";
        const updatedInfo = user3.GetFullInfo();
        
        ({
            originalName: originalName,
            newName: newName,
            infoAfterNameChange: info,
            finalInfo: updatedInfo,
            // Demonstrate that Go object is truly synchronized
            goObjectAge: user3.age,
            goObjectEmail: user3.email_address
        });
    `)
    defer result3.Free()
    fmt.Println("Auto-sync demonstration:", result3.JSONStringify())
}
Advanced Reflection Options

Customize automatic binding with filtering and configuration options:

package main

import (
    "fmt"
    "github.com/buke/quickjs-go"
)

type APIClient struct {
    BaseURL    string `js:"baseUrl"`      // Becomes accessor: client.baseUrl
    APIKey     string `js:"-"`            // Hidden from JavaScript
    Version    string `js:"version"`      // Becomes accessor: client.version
    UserAgent  string `js:"userAgent"`    // Becomes accessor: client.userAgent
}

func (c *APIClient) Get(endpoint string) string {
    return fmt.Sprintf("GET %s%s", c.BaseURL, endpoint)
}

func (c *APIClient) Post(endpoint string, data interface{}) string {
    return fmt.Sprintf("POST %s%s with data", c.BaseURL, endpoint)
}

func (c *APIClient) InternalMethod() string {
    return "This should be hidden"
}

func main() {
    rt := quickjs.NewRuntime()
    defer rt.Close()
    ctx := rt.NewContext()
    defer ctx.Close()

    // Create class with custom options
    clientConstructor, _, err := ctx.BindClass(&APIClient{},
        quickjs.WithMethodPrefix("Get"), // Only include Get* and Post* methods
        quickjs.WithIgnoredMethods("InternalMethod"), // Explicitly ignore methods
        quickjs.WithIgnoredFields("APIKey"), // Ignore additional fields beyond tags
    )
    if err != nil {
        panic(err)
    }

    ctx.Globals().Set("APIClient", clientConstructor)

    result, _ := ctx.Eval(`
        const client = new APIClient({
            baseUrl: "https://api.example.com/v1/",
            version: "1.0",
            userAgent: "MyApp/1.0"
        });
        
        // Field accessors work for all exported fields with automatic sync
        const originalUrl = client.baseUrl;  // Getter
        client.baseUrl = "https://api.example.com/v2/"; // Setter: updates Go struct
        const newUrl = client.baseUrl;       // Getter shows updated value
        
        ({
            get: client.Get("/users"),
            post: typeof client.Post !== 'undefined' ? client.Post("/users", {name: "test"}) : "undefined",
            hasInternal: typeof client.InternalMethod !== 'undefined',
            hasAPIKey: typeof client.APIKey !== 'undefined',
            originalUrl: originalUrl,
            newUrl: newUrl,
            // Field accessor changes are reflected in method calls
            getWithNewUrl: client.Get("/users")
        });
    `)
    defer result.Free()
    
    fmt.Println("Filtered binding with auto-sync:", result.JSONStringify())
}
Class Inheritance Support

JavaScript classes can inherit from Go-registered classes:

package main

import (
    "fmt"
    "github.com/buke/quickjs-go"
)

type Vehicle struct {
    Brand string `js:"brand"`  // Accessor: vehicle.brand
    Model string `js:"model"`  // Accessor: vehicle.model
}

func (v *Vehicle) Start() string {
    return fmt.Sprintf("Starting %s %s", v.Brand, v.Model)
}

func main() {
    rt := quickjs.NewRuntime()
    defer rt.Close()
    ctx := rt.NewContext()
    defer ctx.Close()

    // Register base Vehicle class
    vehicleConstructor, _, _ := ctx.BindClass(&Vehicle{})
    ctx.Globals().Set("Vehicle", vehicleConstructor)

    // Create Car class that extends Vehicle in JavaScript
    _, err := ctx.Eval(`
        class Car extends Vehicle {
            constructor(brand, model, doors) {
                super({ brand, model });
                this.doors = doors;
            }
            
            getInfo() {
                // Inherited field accessors work in JavaScript subclasses with auto-sync
                return this.Start() + " with " + this.doors + " doors";
            }
            
            setBrandAndModel(brand, model) {
                // Field accessors can be used to modify Go struct fields with immediate sync
                this.brand = brand;  // Setter accessor: immediate Go struct update
                this.model = model;  // Setter accessor: immediate Go struct update
            }
        }
        
        // Test inheritance with field accessors and auto-sync
        const car = new Car("Toyota", "Camry", 4);
        const info1 = car.getInfo();
        
        // Modify via inherited field accessors - changes are immediately reflected
        car.setBrandAndModel("Honda", "Accord");
        const info2 = car.getInfo();
        
        globalThis.result = { 
            original: info1, 
            modified: info2,
            brand: car.brand,  // Getter accessor: reads current Go struct value
            model: car.model   // Getter accessor: reads current Go struct value
        };
    `)
    if err != nil {
        panic(err)
    }

    result := ctx.Globals().Get("result")
    defer result.Free()
    fmt.Println("Inheritance with Auto-sync Accessors:", result.JSONStringify())
}
Direct Constructor Calls

Use CallConstructor for direct class instantiation from Go:

package main

import (
    "fmt"
    "github.com/buke/quickjs-go"
)

type Point struct {
    X, Y float64
}

func main() {
    rt := quickjs.NewRuntime()
    defer rt.Close()
    ctx := rt.NewContext()
    defer ctx.Close()

    // Create Point class
    pointConstructor, _, err := quickjs.NewClassBuilder("Point").
        Constructor(func(ctx *quickjs.Context, instance quickjs.Value, args []quickjs.Value) (interface{}, error) {
            x, y := 0.0, 0.0
            if len(args) > 0 { x = args[0].Float64() }
            if len(args) > 1 { y = args[1].Float64() }
            return &Point{X: x, Y: y}, nil
        }).
        Method("toString", func(ctx *quickjs.Context, this quickjs.Value, args []quickjs.Value) quickjs.Value {
            point, _ := this.GetGoObject()
            p := point.(*Point)
            return ctx.String(fmt.Sprintf("Point(%g, %g)", p.X, p.Y))
        }).
        Build(ctx)

    if err != nil {
        panic(err)
    }

    // Direct constructor call from Go
    instance := pointConstructor.CallConstructor(ctx.Float64(10), ctx.Float64(20))
    defer instance.Free()

    // Call method on the instance
    result := instance.Call("toString")
    defer result.Free()

    fmt.Println("Direct call result:", result.String()) // Point(10, 20)

    // Get Go object from JavaScript instance
    goObj, err := instance.GetGoObject()
    if err == nil {
        point := goObj.(*Point)
        fmt.Printf("Go object: {X: %g, Y: %g}\n", point.X, point.Y)
    }
}
Error Handling in Constructors

Handle constructor errors gracefully:

package main

import (
    "fmt"
    "errors"
    "strings"
    "github.com/buke/quickjs-go"
)

type ValidatedUser struct {
    Name  string
    Email string
}

func main() {
    rt := quickjs.NewRuntime()
    defer rt.Close()
    ctx := rt.NewContext()
    defer ctx.Close()

    // Create class with constructor validation
    userConstructor, _, err := quickjs.NewClassBuilder("ValidatedUser").
        Constructor(func(ctx *quickjs.Context, instance quickjs.Value, args []quickjs.Value) (interface{}, error) {
            if len(args) < 2 {
                return nil, errors.New("ValidatedUser requires name and email")
            }
            
            name := args[0].String()
            email := args[1].String()
            
            if name == "" {
                return nil, errors.New("name cannot be empty")
            }
            
            if email == "" || !strings.Contains(email, "@") {
                return nil, errors.New("invalid email address")
            }
            
            return &ValidatedUser{Name: name, Email: email}, nil
        }).
        Method("getInfo", func(ctx *quickjs.Context, this quickjs.Value, args []quickjs.Value) quickjs.Value {
            user, _ := this.GetGoObject()
            u := user.(*ValidatedUser)
            return ctx.String(fmt.Sprintf("%s <%s>", u.Name, u.Email))
        }).
        Build(ctx)

    if err != nil {
        panic(err)
    }

    ctx.Globals().Set("ValidatedUser", userConstructor)

    // Test constructor error handling
    result, _ := ctx.Eval(`
        try {
            const user1 = new ValidatedUser("Alice", "alice@example.com");
            const info1 = user1.getInfo();
            
            const user2 = new ValidatedUser("", "invalid-email");
            const info2 = user2.getInfo();
            
            [info1, info2];
        } catch (error) {
            error.message;
        }
    `)
    defer result.Free()
    
    fmt.Println("Constructor error handling:", result.String())
}
Features

Manual Class Binding:

  • Full control over class structure and behavior
  • Support for instance and static methods/properties
  • Data properties with automatic instance binding
  • Read-only, write-only, and read-write accessors
  • Constructor with error handling and instance pre-creation
  • Automatic memory management with finalizers

Automatic Reflection Binding:

  • Zero-boilerplate class generation from Go structs
  • Smart constructor supporting both positional and named parameters
  • Automatic field-to-accessor mapping: Go struct fields become JavaScript accessors with getter/setter functionality
  • Real-time synchronization: Changes to JavaScript properties immediately update the underlying Go struct fields
  • Bidirectional data binding: Go method calls see JavaScript-side changes instantly
  • Automatic property mapping with js and json tag support
  • Method binding with proper parameter/return value conversion
  • TypedArray support for numeric slice fields
  • Configurable filtering for methods and fields

Key Synchronization Features:

  • Immediate updates: obj.field = value immediately modifies the Go struct field
  • Live data access: Go methods always see the current JavaScript-side values
  • No manual sync required: Changes are automatically propagated between JavaScript and Go
  • Type-safe conversion: Values are properly converted between JavaScript and Go types
  • Memory efficient: Direct field access without intermediate serialization

Shared Features:

  • Full JavaScript inheritance support
  • Seamless integration with Marshal/Unmarshal system
  • TypedArray support for binary data
  • Constructor error handling with JavaScript exceptions
  • Automatic memory management and cleanup
  • Thread-safe operation
  • Class instance validation and type checking
  • Direct constructor calls from Go code
Bytecode Compiler

package main

import (
    "fmt"

    "github.com/buke/quickjs-go"
)

func main() {
    // Create a new runtime
    rt := quickjs.NewRuntime()
    defer rt.Close()
    // Create a new context
    ctx := rt.NewContext()
    defer ctx.Close()

    jsStr := `
    function fib(n)
    {
        if (n <= 0)
            return 0;
        else if (n == 1)
            return 1;
        else
            return fib(n - 1) + fib(n - 2);
    }
    fib(10)
    `
    // Compile the script to bytecode
    buf, _ := ctx.Compile(jsStr)

    // Create a new runtime
    rt2 := quickjs.NewRuntime()
    defer rt2.Close()

    // Create a new context
    ctx2 := rt2.NewContext()
    defer ctx2.Close()

    //Eval bytecode
    result, _ := ctx2.EvalBytecode(buf)
    fmt.Println(result.Int32())
}
Runtime Options: memory, stack, GC, ...
package main

import (
    "fmt"

    "github.com/buke/quickjs-go"
)

func main() {
    // Create a new runtime
    rt := quickjs.NewRuntime()
    defer rt.Close()

    // set runtime options
    rt.SetExecuteTimeout(30) // Set execute timeout to 30 seconds
    rt.SetMemoryLimit(256 * 1024) // Set memory limit to 256KB
    rt.SetMaxStackSize(65534) // Set max stack size to 65534
    rt.SetGCThreshold(256 * 1024) // Set GC threshold to 256KB
    rt.SetCanBlock(true) // Set can block to true

    // Create a new context
    ctx := rt.NewContext()
    defer ctx.Close()

    result, err := ctx.Eval(`var array = []; while (true) { array.push(null) }`)
    defer result.Free()
}
ES6 Module Support

package main

import (
    "fmt"

    "github.com/buke/quickjs-go"
)

func main() {
// enable module import
    rt := quickjs.NewRuntime(quickjs.WithModuleImport(true))
    defer rt.Close()

    ctx := rt.NewContext()
    defer ctx.Close()

    // eval module
    r1, err := ctx.EvalFile("./test/hello_module.js")
    defer r1.Free()
    require.NoError(t, err)
    require.EqualValues(t, 55, ctx.Globals().Get("result").Int32())

    // load module
    r2, err := ctx.LoadModuleFile("./test/fib_module.js", "fib_foo")
    defer r2.Free()
    require.NoError(t, err)

    // call module
    r3, err := ctx.Eval(`
    import {fib} from 'fib_foo';
    globalThis.result = fib(9);
    `)
    defer r3.Free()
    require.NoError(t, err)

    require.EqualValues(t, 34, ctx.Globals().Get("result").Int32())
}

Documentation

Go Reference & more examples: https://pkg.go.dev/github.com/buke/quickjs-go

License

MIT

FOSSA Status

Documentation

Overview

Package quickjs Go bindings to QuickJS: a fast, small, and embeddable ES2020 JavaScript interpreter

Example
package main

import (
	"fmt"

	"github.com/buke/quickjs-go"
)

// User represents a common user struct for demonstrating Marshal and Class features
type User struct {
	ID       int64     `js:"id"`
	Name     string    `js:"name"`
	Email    string    `js:"email"`
	Age      int       `js:"age"`
	IsActive bool      `js:"is_active"`
	Scores   []float32 `js:"scores"` // Demonstrates TypedArray support
}

// GetFullInfo returns the user's full information
func (u *User) GetFullInfo() string {
	return fmt.Sprintf("%s (%s) - Age: %d", u.Name, u.Email, u.Age)
}

// GetAverageScore calculates the average score
func (u *User) GetAverageScore() float64 {
	if len(u.Scores) == 0 {
		return 0
	}
	var sum float32
	for _, score := range u.Scores {
		sum += score
	}
	return float64(sum) / float64(len(u.Scores))
}

func main() {
	// Create a new runtime
	rt := quickjs.NewRuntime()
	defer rt.Close()

	// Create a new context
	ctx := rt.NewContext()
	defer ctx.Close()

	// Create a new object
	test := ctx.Object()
	defer test.Free()
	// bind properties to the object
	test.Set("A", test.Context().String("String A"))
	test.Set("B", ctx.Int32(0))
	test.Set("C", ctx.Bool(false))
	// bind go function to js object
	test.Set("hello", ctx.Function(func(ctx *quickjs.Context, this quickjs.Value, args []quickjs.Value) quickjs.Value {
		return ctx.String("Hello " + args[0].String())
	}))

	// bind "test" object to global object
	ctx.Globals().Set("test", test)

	// call js function by js
	js_ret, _ := ctx.Eval(`test.hello("Javascript!")`)
	defer js_ret.Free()
	fmt.Println(js_ret.String())

	// call js function by go
	go_ret := ctx.Globals().Get("test").Call("hello", ctx.String("Golang!"))
	defer go_ret.Free()
	fmt.Println(go_ret.String())

	// bind go function to Javascript async function using Function + Promise
	ctx.Globals().Set("testAsync", ctx.Function(func(ctx *quickjs.Context, this quickjs.Value, args []quickjs.Value) quickjs.Value {
		return ctx.Promise(func(resolve, reject func(quickjs.Value)) {
			resolve(ctx.String("Hello Async Function!"))
		})
	}))

	ret, _ := ctx.Eval(`
        var ret;
        testAsync().then(v => ret = v)
    `)
	defer ret.Free()

	// wait for promise resolve
	ctx.Loop()

	asyncRet, _ := ctx.Eval("ret")
	defer asyncRet.Free()
	fmt.Println(asyncRet.String())

	// Demonstrate TypedArray functionality
	floatData := []float32{95.5, 87.2, 92.0}
	typedArray := ctx.Float32Array(floatData)
	ctx.Globals().Set("floatData", typedArray)

	arrayResult, _ := ctx.Eval(`floatData instanceof Float32Array`)
	defer arrayResult.Free()
	fmt.Println("TypedArray:", arrayResult.Bool())

	// Demonstrate Marshal/Unmarshal functionality with User struct
	user := User{
		ID:       123,
		Name:     "Alice",
		Email:    "alice@example.com",
		Age:      25,
		IsActive: true,
		Scores:   []float32{95.5, 87.2, 92.0},
	}

	jsVal, _ := ctx.Marshal(user)
	ctx.Globals().Set("userData", jsVal)

	marshalResult, _ := ctx.Eval(`userData.name + " avg: " + (userData.scores.reduce((s,v) => s+v) / userData.scores.length).toFixed(1)`)
	defer marshalResult.Free()
	fmt.Println("Marshal:", marshalResult.String())

	// Demonstrate Class Binding functionality with the same User struct
	userConstructor, _, _ := ctx.BindClass(&User{})
	ctx.Globals().Set("User", userConstructor)

	classResult, _ := ctx.Eval(`
        const user = new User({
            id: 456,
            name: "Bob",
            email: "bob@example.com",
            age: 30,
            is_active: true,
            scores: [88.0, 92.5, 85.0]
        });
        user.GetAverageScore().toFixed(1)
    `)
	defer classResult.Free()
	fmt.Println("Class binding:", classResult.String())

}
Output:

Hello Javascript!
Hello Golang!
Hello Async Function!
TypedArray: true
Marshal: Alice avg: 91.6
Class binding: 88.5

Index

Examples

Constants

View Source
const (
	PropertyConfigurable = 1 << 0 // JS_PROP_CONFIGURABLE
	PropertyWritable     = 1 << 1 // JS_PROP_WRITABLE
	PropertyEnumerable   = 1 << 2 // JS_PROP_ENUMERABLE

	// Default property flags (writable, enumerable, configurable)
	PropertyDefault = PropertyConfigurable | PropertyWritable | PropertyEnumerable
)

Property flags constants matching QuickJS - unchanged

Variables

This section is empty.

Functions

This section is empty.

Types

type AccessorEntry added in v0.5.7

type AccessorEntry struct {
	Name   string          // Accessor name in JavaScript
	Getter ClassGetterFunc // Optional getter function
	Setter ClassSetterFunc // Optional setter function
	Static bool            // true for static accessors, false for instance accessors
}

AccessorEntry represents an accessor binding configuration - unchanged

type Atom

type Atom struct {
	// contains filtered or unexported fields
}

Atom represents a QuickJS atom - unique strings used for object property names. Object property names and some strings are stored as Atoms (unique strings) to save memory and allow fast comparison. Atoms are represented as a 32 bit integer. Half of the atom range is reserved for immediate integer literals from 0 to 2^{31}-1.

func (Atom) Free

func (a Atom) Free()

Free decrements the reference count of the atom.

func (Atom) String

func (a Atom) String() string

String returns the string representation of the atom.

func (Atom) Value

func (a Atom) Value() Value

Value returns the value representation of the atom.

type ClassBuilder added in v0.5.6

type ClassBuilder struct {
	// contains filtered or unexported fields
}

ClassBuilder provides a fluent API for building JavaScript classes Uses builder pattern for easy and readable class definition MODIFIED FOR SCHEME C: Now stores complete class definition including instance properties

func NewClassBuilder added in v0.5.6

func NewClassBuilder(name string) *ClassBuilder

NewClassBuilder creates a new ClassBuilder with the specified name This is the entry point for building JavaScript classes

func (*ClassBuilder) Accessor added in v0.5.7

func (cb *ClassBuilder) Accessor(name string, getter ClassGetterFunc, setter ClassSetterFunc) *ClassBuilder

Accessor adds a read-write accessor to the class instance - unchanged Pass nil for getter to create write-only accessor Pass nil for setter to create read-only accessor

func (*ClassBuilder) Build added in v0.5.6

func (cb *ClassBuilder) Build(ctx *Context) (Value, uint32, error)

Build creates and registers the JavaScript class in the given context Returns the constructor function and classID for NewInstance

func (*ClassBuilder) Constructor added in v0.5.6

func (cb *ClassBuilder) Constructor(fn ClassConstructorFunc) *ClassBuilder

Constructor sets the constructor function for the class MODIFIED FOR SCHEME C: Now uses new constructor signature The constructor function will be called with pre-created instance

func (*ClassBuilder) Method added in v0.5.6

func (cb *ClassBuilder) Method(name string, fn ClassMethodFunc) *ClassBuilder

Method adds an instance method to the class - unchanged Instance methods are called on object instances

func (*ClassBuilder) Property added in v0.5.6

func (cb *ClassBuilder) Property(name string, value Value, flags ...int) *ClassBuilder

Property adds a data property to the class instance - unchanged Default flags: writable, enumerable, configurable SCHEME C: Instance properties will be bound during instance creation

func (*ClassBuilder) StaticAccessor added in v0.5.7

func (cb *ClassBuilder) StaticAccessor(name string, getter ClassGetterFunc, setter ClassSetterFunc) *ClassBuilder

StaticAccessor adds a read-write static accessor to the class constructor - unchanged Pass nil for getter to create write-only accessor Pass nil for setter to create read-only accessor

func (*ClassBuilder) StaticMethod added in v0.5.6

func (cb *ClassBuilder) StaticMethod(name string, fn ClassMethodFunc) *ClassBuilder

StaticMethod adds a static method to the class - unchanged Static methods are called on the constructor function itself

func (*ClassBuilder) StaticProperty added in v0.5.6

func (cb *ClassBuilder) StaticProperty(name string, value Value, flags ...int) *ClassBuilder

StaticProperty adds a data property to the class constructor - unchanged Default flags: writable, enumerable, configurable

type ClassConstructorFunc added in v0.5.6

type ClassConstructorFunc func(ctx *Context, instance Value, args []Value) (interface{}, error)

MODIFIED FOR SCHEME C: ClassConstructorFunc signature changed Constructor now receives pre-created instance and returns Go object to associate This aligns with Scheme C design where instances are pre-created with bound properties

type ClassFinalizer added in v0.5.6

type ClassFinalizer interface {
	Finalize()
}

Optional cleanup interface for class instances Objects implementing this interface will have Finalize() called automatically when the JavaScript object is garbage collected

type ClassGetterFunc added in v0.5.6

type ClassGetterFunc func(ctx *Context, this Value) Value

ClassGetterFunc represents accessor getter functions - unchanged Corresponds to QuickJS JSCFunctionType.getter_magic

type ClassMethodFunc added in v0.5.6

type ClassMethodFunc func(ctx *Context, this Value, args []Value) Value

ClassMethodFunc represents both instance and static methods - unchanged this parameter represents the object instance for instance methods, or the constructor function for static methods Corresponds to QuickJS JSCFunctionType.generic_magic

type ClassSetterFunc added in v0.5.6

type ClassSetterFunc func(ctx *Context, this Value, value Value) Value

ClassSetterFunc represents accessor setter functions - unchanged Returns the set value or an exception Corresponds to QuickJS JSCFunctionType.setter_magic

type Context

type Context struct {
	// contains filtered or unexported fields
}

Context represents a Javascript context (or Realm). Each JSContext has its own global objects and system objects. There can be several JSContexts per JSRuntime and they can share objects, similar to frames of the same origin sharing Javascript objects in a web browser.

func (*Context) ArrayBuffer added in v0.1.13

func (ctx *Context) ArrayBuffer(binaryData []byte) Value

ArrayBuffer returns a ArrayBuffer value with given binary data.

func (*Context) AsyncFunction deprecated added in v0.1.2

func (ctx *Context) AsyncFunction(asyncFn func(ctx *Context, this Value, promise Value, args []Value) Value) Value

AsyncFunction returns a js async function value with given function template

Deprecated: Use Context.Function + Context.Promise instead for better memory management and thread safety. Example:

asyncFn := ctx.Function(func(ctx *quickjs.Context, this quickjs.Value, args []quickjs.Value) quickjs.Value {
    return ctx.Promise(func(resolve, reject func(quickjs.Value)) {
        // async work here
        resolve(ctx.String("result"))
    })
})

func (*Context) Atom

func (ctx *Context) Atom(v string) Atom

Atom returns a new Atom value with given string.

func (*Context) AtomIdx

func (ctx *Context) AtomIdx(idx uint32) Atom

Atom returns a new Atom value with given idx.

func (*Context) Await added in v0.4.8

func (ctx *Context) Await(v Value) (Value, error)

Wait for a promise and execute pending jobs while waiting for it. Return the promise result or JS_EXCEPTION in case of promise rejection.

func (*Context) BigInt64

func (ctx *Context) BigInt64(v int64) Value

BigInt64 returns a int64 value with given uint64.

func (*Context) BigInt64Array added in v0.5.4

func (ctx *Context) BigInt64Array(data []int64) Value

BigInt64Array returns a BigInt64Array value with given int64 slice.

func (*Context) BigUint64

func (ctx *Context) BigUint64(v uint64) Value

BigUint64 returns a uint64 value with given uint64.

func (*Context) BigUint64Array added in v0.5.4

func (ctx *Context) BigUint64Array(data []uint64) Value

BigUint64Array returns a BigUint64Array value with given uint64 slice.

func (*Context) BindClass added in v0.5.6

func (ctx *Context) BindClass(structType interface{}, options ...ReflectOption) (Value, uint32, error)

BindClass automatically creates and builds a JavaScript class from a Go struct type using reflection. This is a convenience method that combines BindClassBuilder and Build. Only exported fields and methods are bound to maintain Go encapsulation principles.

Example usage:

constructor, classID, err := ctx.BindClass(&MyStruct{})
if err != nil { return err }
ctx.Globals().Set("MyStruct", constructor)

func (*Context) BindClassBuilder added in v0.5.6

func (ctx *Context) BindClassBuilder(structType interface{}, options ...ReflectOption) (*ClassBuilder, error)

BindClassBuilder automatically creates a ClassBuilder from a Go struct type using reflection. Returns a ClassBuilder that can be further customized using chain methods before Build(). Only exported fields and methods are analyzed to maintain Go encapsulation principles.

Example usage:

builder, err := ctx.BindClassBuilder(&MyStruct{})
if err != nil { return err }
constructor, classID, err := builder.Build(ctx)

// Or with additional customization:
builder, err := ctx.BindClassBuilder(&MyStruct{})
if err != nil { return err }
constructor, classID, err := builder.
    StaticMethod("Create", myCreateFunc).
    ReadOnlyAccessor("version", myVersionGetter).
    Build(ctx)

func (*Context) Bool

func (ctx *Context) Bool(b bool) Value

Bool returns a bool value with given bool.

func (*Context) Close

func (ctx *Context) Close()

Free will free context and all associated objects.

func (*Context) Compile

func (ctx *Context) Compile(code string, opts ...EvalOption) ([]byte, error)

Compile returns a compiled bytecode with given code.

func (*Context) CompileFile

func (ctx *Context) CompileFile(filePath string, opts ...EvalOption) ([]byte, error)

Compile returns a compiled bytecode with given filename.

func (*Context) CompileModule added in v0.4.14

func (ctx *Context) CompileModule(filePath string, moduleName string, opts ...EvalOption) ([]byte, error)

CompileModule returns a compiled bytecode with given code and module name.

func (*Context) Error

func (ctx *Context) Error(err error) Value

Error returns a new exception value with given message.

func (*Context) Eval

func (ctx *Context) Eval(code string, opts ...EvalOption) (Value, error)

Eval returns a js value with given code. Need call Free() `quickjs.Value`'s returned by `Eval()` and `EvalFile()` and `EvalBytecode()`. func (ctx *Context) Eval(code string) (Value, error) { return ctx.EvalFile(code, "code") }

func (*Context) EvalBytecode

func (ctx *Context) EvalBytecode(buf []byte) (Value, error)

EvalBytecode returns a js value with given bytecode. Need call Free() `quickjs.Value`'s returned by `Eval()` and `EvalFile()` and `EvalBytecode()`.

func (*Context) EvalFile

func (ctx *Context) EvalFile(filePath string, opts ...EvalOption) (Value, error)

EvalFile returns a js value with given code and filename. Need call Free() `quickjs.Value`'s returned by `Eval()` and `EvalFile()` and `EvalBytecode()`.

func (*Context) Exception

func (ctx *Context) Exception() error

Exception returns a context's exception value.

func (*Context) Float32Array added in v0.5.4

func (ctx *Context) Float32Array(data []float32) Value

Float32Array returns a Float32Array value with given float32 slice.

func (*Context) Float64

func (ctx *Context) Float64(v float64) Value

Float64 returns a float64 value with given float64.

func (*Context) Float64Array added in v0.5.4

func (ctx *Context) Float64Array(data []float64) Value

Float64Array returns a Float64Array value with given float64 slice.

func (*Context) Function

func (ctx *Context) Function(fn func(*Context, Value, []Value) Value) Value

Function returns a js function value with given function template New implementation using HandleStore and JS_NewCFunction2 with magic parameter

func (*Context) Globals

func (ctx *Context) Globals() Value

Global returns a context's global object.

func (*Context) HasException added in v0.5.3

func (ctx *Context) HasException() bool

HasException checks if the context has an exception set.

func (*Context) Int16Array added in v0.5.4

func (ctx *Context) Int16Array(data []int16) Value

Int16Array returns a Int16Array value with given int16 slice.

func (*Context) Int32

func (ctx *Context) Int32(v int32) Value

Int32 returns a int32 value with given int32.

func (*Context) Int32Array added in v0.5.4

func (ctx *Context) Int32Array(data []int32) Value

Int32Array returns a Int32Array value with given int32 slice.

func (*Context) Int64

func (ctx *Context) Int64(v int64) Value

Int64 returns a int64 value with given int64.

func (*Context) Int8Array added in v0.5.4

func (ctx *Context) Int8Array(data []int8) Value

Int8Array returns a Int8Array value with given int8 slice.

func (*Context) Invoke added in v0.1.3

func (ctx *Context) Invoke(fn Value, this Value, args ...Value) Value

Invoke invokes a function with given this value and arguments. Deprecated: Use Value.Execute() instead for better API consistency.

func (*Context) LoadModule added in v0.4.10

func (ctx *Context) LoadModule(code string, moduleName string, opts ...EvalOption) (Value, error)

LoadModule returns a js value with given code and module name.

func (*Context) LoadModuleBytecode added in v0.4.10

func (ctx *Context) LoadModuleBytecode(buf []byte, opts ...EvalOption) (Value, error)

LoadModuleByteCode returns a js value with given bytecode and module name.

func (*Context) LoadModuleFile added in v0.4.10

func (ctx *Context) LoadModuleFile(filePath string, moduleName string) (Value, error)

LoadModuleFile returns a js value with given file path and module name.

func (*Context) Loop added in v0.3.3

func (ctx *Context) Loop()

Loop runs the context's event loop.

func (*Context) Marshal added in v0.5.3

func (ctx *Context) Marshal(v interface{}) (Value, error)

Marshal returns the JavaScript value encoding of v. It traverses the value v recursively and creates corresponding JavaScript values.

Marshal uses the following type mappings:

  • bool -> JavaScript boolean
  • int, int8, int16, int32 -> JavaScript number (32-bit)
  • int64 -> JavaScript number (64-bit)
  • uint, uint8, uint16, uint32 -> JavaScript number (32-bit unsigned)
  • uint64 -> JavaScript BigInt
  • float32, float64 -> JavaScript number
  • string -> JavaScript string
  • []byte -> JavaScript ArrayBuffer
  • []int8 -> JavaScript Int8Array
  • []int16 -> JavaScript Int16Array
  • []uint16 -> JavaScript Uint16Array
  • []int32 -> JavaScript Int32Array
  • []uint32 -> JavaScript Uint32Array
  • []float32 -> JavaScript Float32Array
  • []float64 -> JavaScript Float64Array
  • []int64 -> JavaScript BigInt64Array
  • []uint64 -> JavaScript BigUint64Array
  • slice/array -> JavaScript Array
  • map -> JavaScript Object
  • struct -> JavaScript Object
  • pointer -> recursively marshal the pointed value (nil becomes null)

Struct fields are marshaled using their field names unless a tag is present. The "js" and "json" tags are supported. Fields with tag "-" are ignored.

Types implementing the Marshaler interface are marshaled using their MarshalJS method.

func (*Context) Null

func (ctx *Context) Null() Value

Null return a null value.

func (*Context) Object

func (ctx *Context) Object() Value

Object returns a new object value.

func (*Context) ParseJSON added in v0.1.11

func (ctx *Context) ParseJSON(v string) Value

ParseJson parses given json string and returns a object value.

func (*Context) Promise added in v0.5.5

func (ctx *Context) Promise(executor func(resolve, reject func(Value))) Value

Promise creates a new Promise with executor function Executor runs synchronously in current thread for thread safety

func (*Context) Runtime added in v0.4.6

func (ctx *Context) Runtime() *Runtime

Runtime returns the runtime of the context.

func (*Context) SetInterruptHandler deprecated added in v0.1.14

func (ctx *Context) SetInterruptHandler(handler InterruptHandler)

SetInterruptHandler sets a interrupt handler.

Deprecated: Use SetInterruptHandler on runtime instead

func (*Context) String

func (ctx *Context) String(v string) Value

String returns a string value with given string.

func (*Context) Throw

func (ctx *Context) Throw(v Value) Value

Throw returns a context's exception value.

func (*Context) ThrowError

func (ctx *Context) ThrowError(err error) Value

ThrowError returns a context's exception value with given error message.

func (*Context) ThrowInternalError

func (ctx *Context) ThrowInternalError(format string, args ...interface{}) Value

ThrowInternalError returns a context's exception value with given error message.

func (*Context) ThrowRangeError

func (ctx *Context) ThrowRangeError(format string, args ...interface{}) Value

ThrowRangeError returns a context's exception value with given error message.

func (*Context) ThrowReferenceError

func (ctx *Context) ThrowReferenceError(format string, args ...interface{}) Value

ThrowReferenceError returns a context's exception value with given error message.

func (*Context) ThrowSyntaxError

func (ctx *Context) ThrowSyntaxError(format string, args ...interface{}) Value

ThrowSyntaxError returns a context's exception value with given error message.

func (*Context) ThrowTypeError

func (ctx *Context) ThrowTypeError(format string, args ...interface{}) Value

ThrowTypeError returns a context's exception value with given error message.

func (*Context) Uint16Array added in v0.5.4

func (ctx *Context) Uint16Array(data []uint16) Value

Uint16Array returns a Uint16Array value with given uint16 slice.

func (*Context) Uint32

func (ctx *Context) Uint32(v uint32) Value

Uint32 returns a uint32 value with given uint32.

func (*Context) Uint32Array added in v0.5.4

func (ctx *Context) Uint32Array(data []uint32) Value

Uint32Array returns a Uint32Array value with given uint32 slice.

func (*Context) Uint8Array added in v0.5.4

func (ctx *Context) Uint8Array(data []uint8) Value

Uint8Array returns a Uint8Array value with given uint8 slice.

func (*Context) Uint8ClampedArray added in v0.5.4

func (ctx *Context) Uint8ClampedArray(data []uint8) Value

Uint8ClampedArray returns a Uint8ClampedArray value with given uint8 slice.

func (*Context) Undefined

func (ctx *Context) Undefined() Value

Undefined return a undefined value.

func (*Context) Uninitialized

func (ctx *Context) Uninitialized() Value

Uninitialized returns a uninitialized value.

func (*Context) Unmarshal added in v0.5.3

func (ctx *Context) Unmarshal(jsVal Value, v interface{}) error

Unmarshal parses the JavaScript value and stores the result in the value pointed to by v. If v is nil or not a pointer, Unmarshal returns an error.

Unmarshal uses the inverse of the encodings that Marshal uses, with the following additional rules:

  • JavaScript null/undefined -> Go nil pointer or zero value
  • JavaScript Array -> Go slice/array
  • JavaScript Object -> Go map/struct
  • JavaScript number -> Go numeric types (with appropriate conversion)
  • JavaScript BigInt -> Go uint64/int64/*big.Int
  • JavaScript ArrayBuffer -> Go []byte
  • JavaScript Int8Array -> Go []int8
  • JavaScript Int16Array -> Go []int16
  • JavaScript Uint16Array -> Go []uint16
  • JavaScript Int32Array -> Go []int32
  • JavaScript Uint32Array -> Go []uint32
  • JavaScript Float32Array -> Go []float32
  • JavaScript Float64Array -> Go []float64
  • JavaScript BigInt64Array -> Go []int64
  • JavaScript BigUint64Array -> Go []uint64

When unmarshaling into an interface{}, Unmarshal stores one of:

  • nil for JavaScript null/undefined
  • bool for JavaScript boolean
  • int64 for JavaScript integer numbers
  • float64 for JavaScript floating-point numbers
  • string for JavaScript string
  • []interface{} for JavaScript Array
  • map[string]interface{} for JavaScript Object

Types implementing the Unmarshaler interface are unmarshaled using their UnmarshalJS method.

type Error

type Error struct {
	Name       string // Error name (e.g., "TypeError", "ReferenceError")
	Message    string // Error message
	Cause      string // Error cause
	Stack      string // Stack trace
	JSONString string // Serialized JSON string
}

Error represents a JavaScript error with detailed information.

func (Error) Error

func (err Error) Error() string

Error implements the error interface.

type EvalOption added in v0.4.10

type EvalOption func(*EvalOptions)

func EvalAwait added in v0.4.10

func EvalAwait(await bool) EvalOption

func EvalFileName added in v0.4.10

func EvalFileName(filename string) EvalOption

func EvalFlagCompileOnly added in v0.4.10

func EvalFlagCompileOnly(compileOnly bool) EvalOption

func EvalFlagGlobal added in v0.4.10

func EvalFlagGlobal(global bool) EvalOption

func EvalFlagModule added in v0.4.10

func EvalFlagModule(module bool) EvalOption

func EvalFlagStrict added in v0.4.10

func EvalFlagStrict(strict bool) EvalOption

func EvalLoadOnly added in v0.5.3

func EvalLoadOnly(loadOnly bool) EvalOption

type EvalOptions added in v0.4.10

type EvalOptions struct {
	// contains filtered or unexported fields
}

type FieldTagInfo added in v0.5.6

type FieldTagInfo struct {
	Name      string // JavaScript property name
	Skip      bool   // Whether to skip this field
	OmitEmpty bool   // Whether to omit empty values (for serialization)
}

FieldTagInfo contains parsed field tag information

type InterruptHandler added in v0.1.14

type InterruptHandler func() int

InterruptHandler is a function type for interrupt handler. Return != 0 if the JS code needs to be interrupted

type Marshaler added in v0.5.3

type Marshaler interface {
	MarshalJS(ctx *Context) (Value, error)
}

Marshaler is the interface implemented by types that can marshal themselves into a JavaScript value.

type MethodEntry added in v0.5.6

type MethodEntry struct {
	Name   string          // Method name in JavaScript
	Func   ClassMethodFunc // Method implementation function
	Static bool            // true for static methods, false for instance methods
	Length int             // Expected parameter count, 0 for default
}

MethodEntry represents a method binding configuration - unchanged

type Option added in v0.4.7

type Option func(*Options)

func WithCanBlock added in v0.4.7

func WithCanBlock(canBlock bool) Option

WithCanBlock will set the runtime's can block; default is true

func WithExecuteTimeout added in v0.4.7

func WithExecuteTimeout(timeout uint64) Option

WithExecuteTimeout will set the runtime's execute timeout; default is 0

func WithGCThreshold added in v0.4.7

func WithGCThreshold(gcThreshold int64) Option

WithGCThreshold will set the runtime's GC threshold; default is -1 to disable automatic GC.

func WithMaxStackSize added in v0.4.7

func WithMaxStackSize(maxStackSize uint64) Option

WithMaxStackSize will set max runtime's stack size; default is 0 disable maximum stack size check

func WithMemoryLimit added in v0.4.7

func WithMemoryLimit(memoryLimit uint64) Option

WithMemoryLimit will set the runtime memory limit; if not set, it will be unlimit.

func WithModuleImport added in v0.4.10

func WithModuleImport(moduleImport bool) Option

func WithStripInfo added in v0.5.0

func WithStripInfo(strip int) Option

type Options added in v0.4.7

type Options struct {
	// contains filtered or unexported fields
}

type PromiseState added in v0.5.5

type PromiseState int

Promise state enumeration matching QuickJS

const (
	PromisePending PromiseState = iota
	PromiseFulfilled
	PromiseRejected
)

type PropertyEntry added in v0.5.6

type PropertyEntry struct {
	Name   string // Property name in JavaScript
	Value  Value  // Property value (JavaScript Value)
	Static bool   // true for static properties, false for instance properties
	Flags  int    // Property flags (writable, enumerable, configurable)
}

PropertyEntry represents a property binding configuration - unchanged

type ReflectOption added in v0.5.6

type ReflectOption func(*ReflectOptions)

ReflectOption configures ReflectOptions using functional options pattern

func WithIgnoredFields added in v0.5.6

func WithIgnoredFields(fields ...string) ReflectOption

WithIgnoredFields specifies field names to skip during binding

func WithIgnoredMethods added in v0.5.6

func WithIgnoredMethods(methods ...string) ReflectOption

WithIgnoredMethods specifies method names to skip during binding

func WithMethodPrefix added in v0.5.6

func WithMethodPrefix(prefix string) ReflectOption

WithMethodPrefix filters methods by name prefix

type ReflectOptions added in v0.5.6

type ReflectOptions struct {
	// MethodPrefix filters methods by prefix (empty = all methods)
	MethodPrefix string

	// IgnoredMethods lists method names to skip during binding
	IgnoredMethods []string

	// IgnoredFields lists field names to skip during binding
	IgnoredFields []string
}

ReflectOptions configures automatic class binding behavior

type Runtime

type Runtime struct {
	// contains filtered or unexported fields
}

Runtime represents a Javascript runtime with simplified interrupt handling

func NewRuntime

func NewRuntime(opts ...Option) *Runtime

NewRuntime creates a new quickjs runtime with simplified interrupt handling.

func (*Runtime) ClearInterruptHandler added in v0.5.5

func (r *Runtime) ClearInterruptHandler()

ClearInterruptHandler clears the user interrupt handler

func (*Runtime) Close

func (r *Runtime) Close()

Close will free the runtime pointer with proper cleanup.

func (*Runtime) NewContext

func (r *Runtime) NewContext() *Context

NewContext creates a new JavaScript context.

func (*Runtime) RunGC

func (r *Runtime) RunGC()

RunGC will call quickjs's garbage collector.

func (*Runtime) SetCanBlock added in v0.4.7

func (r *Runtime) SetCanBlock(canBlock bool)

SetCanBlock will set the runtime's can block; default is true

func (*Runtime) SetExecuteTimeout added in v0.4.7

func (r *Runtime) SetExecuteTimeout(timeout uint64)

SetExecuteTimeout will set the runtime's execute timeout; This will override any user interrupt handler (expected behavior)

func (*Runtime) SetGCThreshold

func (r *Runtime) SetGCThreshold(threshold int64)

SetGCThreshold the runtime's GC threshold; use -1 to disable automatic GC.

func (*Runtime) SetInterruptHandler added in v0.5.0

func (r *Runtime) SetInterruptHandler(handler InterruptHandler)

SetInterruptHandler sets a user interrupt handler using simplified approach. This will override any timeout handler (expected behavior)

func (*Runtime) SetMaxStackSize

func (r *Runtime) SetMaxStackSize(stack_size uint64)

SetMaxStackSize will set max runtime's stack size;

func (*Runtime) SetMemoryLimit

func (r *Runtime) SetMemoryLimit(limit uint64)

SetMemoryLimit the runtime memory limit; if not set, it will be unlimit.

func (*Runtime) SetStripInfo added in v0.5.0

func (r *Runtime) SetStripInfo(strip int)

type Unmarshaler added in v0.5.3

type Unmarshaler interface {
	UnmarshalJS(ctx *Context, val Value) error
}

Unmarshaler is the interface implemented by types that can unmarshal a JavaScript value into themselves.

type Value

type Value struct {
	// contains filtered or unexported fields
}

Value represents a Javascript value which can be a primitive type or an object. Reference counting is used, so it is important to explicitly duplicate (JS_DupValue(), increment the reference count) or free (JS_FreeValue(), decrement the reference count) JSValues.

func (Value) Await added in v0.5.5

func (v Value) Await() (Value, error)

Await waits for promise resolution and executes pending jobs Similar to Context.Await but called on Value directly

func (Value) BigInt deprecated

func (v Value) BigInt() *big.Int

Deprecated: Use ToBigInt instead.

func (Value) Bool deprecated

func (v Value) Bool() bool

Deprecated: Use ToBool instead.

func (Value) ByteLen added in v0.1.13

func (v Value) ByteLen() int64

ByteLen returns the length of the ArrayBuffer.

func (Value) Call

func (v Value) Call(fname string, args ...Value) Value

Call calls the function with the given arguments.

func (Value) CallConstructor added in v0.4.15

func (v Value) CallConstructor(args ...Value) Value

CallConstructor calls the constructor with the given arguments. SCHEME C: For class instances, use this method to create instances. The class constructor function will receive a pre-created instance and initialize it. Instance properties declared in ClassBuilder.Property() are automatically bound to the instance.

Example usage:

constructor := ctx.Eval("MyClass")
instance := constructor.CallConstructor(arg1, arg2)

This replaces the previous NewInstance method and provides automatic property binding and simplified constructor semantics where constructors work with pre-created instances.

func (Value) Context

func (v Value) Context() *Context

Context returns the context of the value.

func (Value) Delete

func (v Value) Delete(name string) bool

Delete deletes the property with the given name.

func (Value) DeleteIdx

func (v Value) DeleteIdx(idx uint32) bool

DeleteIdx deletes the property with the given index.

func (Value) Error deprecated

func (v Value) Error() error

Deprecated: Use ToError() instead.

func (Value) Execute added in v0.5.0

func (v Value) Execute(this Value, args ...Value) Value

Execute the function with the given arguments.

func (Value) Float64 deprecated

func (v Value) Float64() float64

Deprecated: Use ToFloat64 instead.

func (Value) Free

func (v Value) Free()

Free the value.

func (Value) Get

func (v Value) Get(name string) Value

Get returns the value of the property with the given name.

func (Value) GetClassID added in v0.5.6

func (v Value) GetClassID() uint32

GetClassID returns the class ID of the value if it's a class instance Returns JS_INVALID_CLASS_ID (0) if not a class instance

func (Value) GetGoObject added in v0.5.6

func (v Value) GetGoObject() (interface{}, error)

GetGoObject retrieves Go object from JavaScript class instance This method extracts the opaque data stored by the constructor proxy

func (Value) GetIdx

func (v Value) GetIdx(idx int64) Value

GetIdx returns the value of the property with the given index.

func (Value) GlobalInstanceof added in v0.5.0

func (v Value) GlobalInstanceof(name string) bool

GlobalInstanceof checks if the value is an instance of the given global constructor

func (Value) Has

func (v Value) Has(name string) bool

Has returns true if the value has the property with the given name.

func (Value) HasIdx

func (v Value) HasIdx(idx uint32) bool

HasIdx returns true if the value has the property with the given index.

func (Value) HasInstanceData added in v0.5.6

func (v Value) HasInstanceData() bool

HasInstanceData checks if the value has associated Go object data This is the most reliable way to identify our class instances

func (Value) Int32 deprecated

func (v Value) Int32() int32

Deprecated: Use ToInt32 instead.

func (Value) Int64 deprecated

func (v Value) Int64() int64

Deprecated: Use ToInt64 instead.

func (Value) IsArray

func (v Value) IsArray() bool

func (Value) IsBigInt

func (v Value) IsBigInt() bool

func (Value) IsBigInt64Array added in v0.5.4

func (v Value) IsBigInt64Array() bool

func (Value) IsBigUint64Array added in v0.5.4

func (v Value) IsBigUint64Array() bool

func (Value) IsBool

func (v Value) IsBool() bool

func (Value) IsByteArray added in v0.1.13

func (v Value) IsByteArray() bool

IsByteArray returns true if the value is array buffer

func (Value) IsClassInstance added in v0.5.6

func (v Value) IsClassInstance() bool

IsClassInstance checks if the value is an instance of any user-defined class This method uses opaque data validation for maximum reliability

func (Value) IsConstructor added in v0.4.15

func (v Value) IsConstructor() bool

func (Value) IsError

func (v Value) IsError() bool

func (Value) IsException

func (v Value) IsException() bool

func (Value) IsFloat32Array added in v0.5.4

func (v Value) IsFloat32Array() bool

func (Value) IsFloat64Array added in v0.5.4

func (v Value) IsFloat64Array() bool

func (Value) IsFunction

func (v Value) IsFunction() bool

func (Value) IsInstanceOfClassID added in v0.5.6

func (v Value) IsInstanceOfClassID(expectedClassID uint32) bool

IsInstanceOfClassID checks if the value is an instance of a specific class ID This provides type-safe class instance checking with double validation

func (Value) IsInstanceOfConstructor added in v0.5.6

func (v Value) IsInstanceOfConstructor(constructor Value) bool

IsInstanceOfConstructor checks if the value is an instance of a specific constructor This uses JavaScript's instanceof operator semantics

func (Value) IsInt16Array added in v0.5.4

func (v Value) IsInt16Array() bool

func (Value) IsInt32Array added in v0.5.4

func (v Value) IsInt32Array() bool

func (Value) IsInt8Array added in v0.5.4

func (v Value) IsInt8Array() bool

func (Value) IsNull

func (v Value) IsNull() bool

func (Value) IsNumber

func (v Value) IsNumber() bool

func (Value) IsObject

func (v Value) IsObject() bool

func (Value) IsPromise added in v0.4.9

func (v Value) IsPromise() bool

func (Value) IsString

func (v Value) IsString() bool

func (Value) IsSymbol

func (v Value) IsSymbol() bool

func (Value) IsTypedArray added in v0.5.4

func (v Value) IsTypedArray() bool

TypedArray detection methods

func (Value) IsUint16Array added in v0.5.4

func (v Value) IsUint16Array() bool

func (Value) IsUint32Array added in v0.5.4

func (v Value) IsUint32Array() bool

func (Value) IsUint8Array added in v0.5.4

func (v Value) IsUint8Array() bool

func (Value) IsUint8ClampedArray added in v0.5.4

func (v Value) IsUint8ClampedArray() bool

func (Value) IsUndefined

func (v Value) IsUndefined() bool

func (Value) IsUninitialized

func (v Value) IsUninitialized() bool

func (Value) JSONStringify added in v0.1.11

func (v Value) JSONStringify() string

JSONStringify returns the JSON string representation of the value.

func (Value) Len

func (v Value) Len() int64

Len returns the length of the array.

func (Value) New added in v0.4.15

func (v Value) New(args ...Value) Value

New calls the constructor with the given arguments.

func (Value) PromiseState added in v0.5.5

func (v Value) PromiseState() PromiseState

PromiseState returns the state of the Promise

func (Value) PropertyNames

func (v Value) PropertyNames() ([]string, error)

PropertyNames returns the names of the properties of the value.

func (Value) Set

func (v Value) Set(name string, val Value)

Set sets the value of the property with the given name.

func (Value) SetIdx

func (v Value) SetIdx(idx int64, val Value)

SetIdx sets the value of the property with the given index.

func (Value) String

func (v Value) String() string

String returns the string representation of the value. This method implements the fmt.Stringer interface.

func (Value) ToBigInt added in v0.5.0

func (v Value) ToBigInt() *big.Int

ToBigInt returns the big.Int value of the value.

func (Value) ToBigInt64Array added in v0.5.4

func (v Value) ToBigInt64Array() ([]int64, error)

ToBigInt64Array converts the value to int64 slice if it's a BigInt64Array.

func (Value) ToBigUint64Array added in v0.5.4

func (v Value) ToBigUint64Array() ([]uint64, error)

ToBigUint64Array converts the value to uint64 slice if it's a BigUint64Array.

func (Value) ToBool added in v0.5.0

func (v Value) ToBool() bool

ToBool returns the boolean value of the value.

func (Value) ToByteArray added in v0.1.13

func (v Value) ToByteArray(size uint) ([]byte, error)

func (Value) ToError added in v0.5.0

func (v Value) ToError() error

ToError returns the error value of the value.

func (Value) ToFloat32Array added in v0.5.4

func (v Value) ToFloat32Array() ([]float32, error)

ToFloat32Array converts the value to float32 slice if it's a Float32Array.

func (Value) ToFloat64 added in v0.5.0

func (v Value) ToFloat64() float64

ToFloat64 returns the float64 value of the value.

func (Value) ToFloat64Array added in v0.5.4

func (v Value) ToFloat64Array() ([]float64, error)

ToFloat64Array converts the value to float64 slice if it's a Float64Array.

func (Value) ToInt16Array added in v0.5.4

func (v Value) ToInt16Array() ([]int16, error)

ToInt16Array converts the value to int16 slice if it's an Int16Array.

func (Value) ToInt32 added in v0.5.0

func (v Value) ToInt32() int32

ToInt32 returns the int32 value of the value.

func (Value) ToInt32Array added in v0.5.4

func (v Value) ToInt32Array() ([]int32, error)

ToInt32Array converts the value to int32 slice if it's an Int32Array.

func (Value) ToInt64 added in v0.5.0

func (v Value) ToInt64() int64

ToInt64 returns the int64 value of the value.

func (Value) ToInt8Array added in v0.5.4

func (v Value) ToInt8Array() ([]int8, error)

ToInt8Array converts the value to int8 slice if it's an Int8Array.

func (Value) ToString added in v0.5.0

func (v Value) ToString() string

ToString returns the string representation of the value.

func (Value) ToUint16Array added in v0.5.4

func (v Value) ToUint16Array() ([]uint16, error)

ToUint16Array converts the value to uint16 slice if it's a Uint16Array.

func (Value) ToUint32 added in v0.5.0

func (v Value) ToUint32() uint32

ToUint32 returns the uint32 value of the value.

func (Value) ToUint32Array added in v0.5.4

func (v Value) ToUint32Array() ([]uint32, error)

ToUint32Array converts the value to uint32 slice if it's a Uint32Array.

func (Value) ToUint8Array added in v0.5.4

func (v Value) ToUint8Array() ([]uint8, error)

ToUint8Array converts the value to uint8 slice if it's a Uint8Array or Uint8ClampedArray.

func (Value) Uint32 deprecated

func (v Value) Uint32() uint32

Deprecated: Use ToUint32 instead.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL