首页
/ 深入理解Goja中如何获取JavaScript类的属性和方法

深入理解Goja中如何获取JavaScript类的属性和方法

2025-06-04 08:01:44作者:俞予舒Fleming

Goja是一个纯Go实现的JavaScript引擎,它提供了在Go环境中运行JavaScript代码的能力。在实际开发中,我们经常需要动态获取JavaScript类的属性和方法列表,这在插件系统、动态调用等场景下非常有用。

获取实例属性

在Goja中,我们可以直接通过Object.Keys()方法获取一个对象实例的所有可枚举属性:

vm := goja.New()
_, err := vm.RunString(`
    class MyClass {
        constructor() {
            this.i = 0;
        }
        DoThing() {
            this.i++;
            return this.i;
        }
    }
`)
if err != nil {
    panic(err)
}

myClassConstructor := vm.Get("MyClass").ToObject(vm)
myClassInstance, err := vm.New(myClassConstructor)
if err != nil {
    panic(err)
}

fmt.Println(myClassInstance.Keys()) // 输出: [i]

这种方法只能获取到实例自身的属性,无法获取到类方法。

获取类方法

JavaScript中的类方法实际上是定义在类的原型(prototype)上的。要获取这些方法,我们需要访问类的prototype对象:

// 获取类的prototype对象
classPrototype := myClassConstructor.Get("prototype").ToObject(vm)

// 使用Object.getOwnPropertyNames获取所有属性(包括不可枚举的)
getOwnPropertyNames, ok := goja.AssertFunction(vm.Get("Object").ToObject(vm).Get("getOwnPropertyNames"))
if !ok {
    panic("Object.getOwnPropertyNames is not a function")
}

array, err := getOwnPropertyNames(nil, classPrototype)
if err != nil {
    panic(err)
}

// 遍历获取所有方法名
for i := 0; i < array.ToObject(vm).Get("length").ToInteger(); i++ {
    methodName := array.ToObject(vm).Get(strconv.Itoa(i)).String()
    fmt.Println(methodName) // 输出: constructor, DoThing
}

原理分析

在JavaScript中,类的方法实际上是定义在prototype对象上的非枚举属性。这就是为什么直接使用Keys()方法无法获取到它们的原因。

  • Class.prototype:存储了类的所有实例方法
  • instance.__proto__:指向Class.prototype,所以实例可以访问这些方法
  • Class.__proto__:指向Function.prototype,因为类本身就是函数

最佳实践

在实际开发中,建议封装一个工具函数来获取类的所有方法和属性:

func GetClassMethods(vm *goja.Runtime, className string) ([]string, error) {
    classConstructor := vm.Get(className)
    if classConstructor == nil {
        return nil, fmt.Errorf("class %s not found", className)
    }
    
    classPrototype := classConstructor.ToObject(vm).Get("prototype")
    if classPrototype == nil {
        return nil, fmt.Errorf("could not get prototype for %s", className)
    }
    
    getOwnPropertyNames, ok := goja.AssertFunction(vm.Get("Object").ToObject(vm).Get("getOwnPropertyNames"))
    if !ok {
        return nil, fmt.Errorf("Object.getOwnPropertyNames is not a function")
    }
    
    array, err := getOwnPropertyNames(nil, classPrototype)
    if err != nil {
        return nil, err
    }
    
    var methods []string
    length := array.ToObject(vm).Get("length").ToInteger()
    for i := 0; i < length; i++ {
        methods = append(methods, array.ToObject(vm).Get(strconv.Itoa(i)).String())
    }
    
    return methods, nil
}

通过这种方式,我们可以方便地在Go代码中动态获取JavaScript类定义的所有方法,为构建更灵活的跨语言交互系统提供了基础。

登录后查看全文
热门项目推荐
相关项目推荐