ottoGo Go 中的 JS 解释器开源项目

我要开发同款
匿名用户2018年04月04日
39阅读
开发技术GO语言
所属分类Google Go、语法解析工具、开发工具
授权协议MIT

作品详情

otto是用原生Go编写的JavaScript解析器和解释器。

import (   "github.com/robertkrimen/otto")

在VM中运行

vm := otto.New()vm.Run(`    abc = 2 + 2;    console.log("The value of abc is " + abc); // 4`)

获取VM外的值

if value, err := vm.Get("abc"); err == nil {    if value_int, err := value.ToInteger(); err == nil {fmt.Printf("", value_int, err)    }}

设置数字

vm.Set("def", 11)vm.Run(`    console.log("The value of def is " + def);    // The value of def is 11`)

设置字符串

vm.Set("xyzzy", "Nothing happens.")vm.Run(`    console.log(xyzzy.length); // 16`)

获取表达式的值

value, _ = vm.Run("xyzzy.length"){    // value is an int64 with a value of 16    value, _ := value.ToInteger()}

抛出错误

value, err = vm.Run("abcdefghijlmnopqrstuvwxyz.length")if err != nil {    // err = ReferenceError: abcdefghijlmnopqrstuvwxyz is not defined    // If there is an error, then value.IsUndefined() is true    ...}

设置Go函数

vm.Set("sayHello", func(call otto.FunctionCall) otto.Value {    fmt.Printf("Hello, %s.\n", call.Argument(0).String())    return otto.Value{}})

在JS中使用函数

result, _ = vm.Run(`    sayHello("Xyzzy");      // Hello, Xyzzy.    sayHello();             // Hello, undefined    result = twoPlus(2.0); // 4`)
查看全文
声明:本文仅代表作者观点,不代表本站立场。如果侵犯到您的合法权益,请联系我们删除侵权资源!如果遇到资源链接失效,请您通过评论或工单的方式通知管理员。未经允许,不得转载,本站所有资源文章禁止商业使用运营!
下载安装【程序员客栈】APP
实时对接需求、及时收发消息、丰富的开放项目需求、随时随地查看项目状态

评论