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

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

2025-06-04 09:26:50作者:俞予舒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类定义的所有方法,为构建更灵活的跨语言交互系统提供了基础。

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

热门内容推荐

最新内容推荐

项目优选

收起
ohos_react_nativeohos_react_native
React Native鸿蒙化仓库
C++
176
261
RuoYi-Vue3RuoYi-Vue3
🎉 (RuoYi)官方仓库 基于SpringBoot,Spring Security,JWT,Vue3 & Vite、Element Plus 的前后端分离权限管理系统
Vue
861
511
ShopXO开源商城ShopXO开源商城
🔥🔥🔥ShopXO企业级免费开源商城系统,可视化DIY拖拽装修、包含PC、H5、多端小程序(微信+支付宝+百度+头条&抖音+QQ+快手)、APP、多仓库、多商户、多门店、IM客服、进销存,遵循MIT开源协议发布、基于ThinkPHP8框架研发
JavaScript
93
15
openGauss-serveropenGauss-server
openGauss kernel ~ openGauss is an open source relational database management system
C++
129
182
openHiTLSopenHiTLS
旨在打造算法先进、性能卓越、高效敏捷、安全可靠的密码套件,通过轻量级、可剪裁的软件技术架构满足各行业不同场景的多样化要求,让密码技术应用更简单,同时探索后量子等先进算法创新实践,构建密码前沿技术底座!
C
259
300
kernelkernel
deepin linux kernel
C
22
5
cherry-studiocherry-studio
🍒 Cherry Studio 是一款支持多个 LLM 提供商的桌面客户端
TypeScript
596
57
CangjieCommunityCangjieCommunity
为仓颉编程语言开发者打造活跃、开放、高质量的社区环境
Markdown
1.07 K
0
HarmonyOS-ExamplesHarmonyOS-Examples
本仓将收集和展示仓颉鸿蒙应用示例代码,欢迎大家投稿,在仓颉鸿蒙社区展现你的妙趣设计!
Cangjie
398
371
Cangjie-ExamplesCangjie-Examples
本仓将收集和展示高质量的仓颉示例代码,欢迎大家投稿,让全世界看到您的妙趣设计,也让更多人通过您的编码理解和喜爱仓颉语言。
Cangjie
332
1.08 K