原文: https://www.fknsrs.biz/blog/otto-getting-started.html.html

GETTING STARTED WITH THE OTTO JAVASCRIPT INTERPRETER
May 2, 2016
 

6 minutes read

While you're reading this, keep in mind that I'm available for hire! If you've got a JavaScript project getting out of hand, or a Golang program that's more "stop" than "go," feel free to get in touch with me. I might be able to help you. You can find my resume here.

JavaScript is by far the most popular scripting language around right now. Born in a web browser, it’s been leaking out into the rest of the software ecosystem for about ten years. JavaScript is great for expressing short pieces of logic, and for prototyping. There are a range of high quality, open source JavaScript engines available for various purposes. The most popular is probably V8, powering projects like node.js and the Atom text editor. While V8 is an incredibly well-optimised piece of software, and there are several bindings of it to Go, the API isn’t very well-suited to close integration with the Go language. Luckily, we have a solid JavaScript engine written in pure Go. It’s called otto, and I’d like to teach you the very basics of using it.

There are a few important things you need to know if you’d like to use otto. The first is that it’s purely an interpreter - there’s no JIT compilation or fancy optimisations. While performance is important, the primary focus of otto is on rich integration with Go. The second is that (right now!) it strictly targets ES5, the fifth edition of the ECMAScript standard, ECMA-262. This is relevant because ECMA-262 actually doesn’t define an event or I/O model. This means thatsetTimeoutsetIntervalXMLHttpRequestfetch, and any other related things are provided by external packages (e.g. fknsrs.biz/p/ottoext). There are a handful of browser APIs in otto (like the console object), but for the most part, if it’s not in ECMA-262, it’s not in otto.

So! Now that we have that out of the way, let’s get into some specifics. First, I’ll describe some important parts of the API. Then we’ll take that information and make a real program out of it!

API

I’m going to be leaving a lot of functions out of this description. For a full listing of what’s available, check out the godoc page.

I’ll also be skipping error checking in these examples, but that’s just to save space. The full program listing below will include error handling.

type Otto

var vm otto.Otto

This type represents an interpreter instance. This is what you’ll use to actually run your JavaScript code. You can think of it as a tiny little self- contained JavaScript universe.

You can interact with this little universe in a variety of ways. You can put things into it (Set), grab things out of it (Get), and of course, run code in it (Run).

func New() Otto

vm := otto.New()

The New function is used to create an Otto instance. There’s some setup that has to happen, so you have to use this constructor function.

func (Otto) Set(name string, v interface{}) error

vm.Set("cool", true)

vm.Set("greet", func(name string) {
return fmt.Printf("hello, %s!\n", name)
})

You can use Set to set global variables in the interpreter. v can be a lot of different things. For simple values (strings, numbers, booleans, nil), you can probably guess what happens.

If v is a more complex, but still built-in type (slice, map), it’ll be turned into the equivalent JavaScript value. For a slice, that’ll be an array. For a map, it’ll be an object.

If v is a struct, it’ll be passed through to the interpreter as an object with properties that refer to the fields and functions of that struct.

If v is a function, otto will map it through to a JavaScript function in the interpreter. Stay tuned for a more detailed article about this in the near future!

Under the hood, this actually uses a function called ToValue.

func (Otto) Run(src interface{}) (Value, error)

vm.Run(`var a = 1;`)

The most obvious way to run code in the interpreter is the Run function. This can take a string, a precompiled Script object, an io.Reader, or a Program. The simplest option is a string, so that’s what we’ll be working with.

Run will always run code in global scope. There’s also an Eval method that will run code in the current interpreter scope, but I won’t be covering that in this article.

func (Otto) Get(name string) (Value, error)

val, _ := vm.Get("greet")

This is one way to get output from the interpreter. Get will reach in and grab things out of the global scope. One important thing about this is that you can’t use Get to retrieve variables that are declared inside functions.

func (Value) Export() (interface{}, error)

a, _ := val.Export()
fmt.Printf("%#v\n", a) // prints `1`

Export does the inverse of what happens when you Set a value. Instead of taking a Go value and making it into a JavaScript value, it makes a JavaScript value into something you can use in Go code.

func (Value) Call(this Value, args …interface{}) (Value, error)

fn, _ := vm.Get("greet")
fn.Call(otto.NullValue(), "friends")

Call only works with functions. If you have a handle to a JavaScript function, you can execute it with a given context (i.e. this value) and optionally some arguments.

The arguments are converted in the same way as the Set function.

Call returns (Value, error). The Value is the return value of the JavaScript function. If the JavaScript code throws an exception, or there’s an internal error in otto, the error value will be non-nil.

There also exists a Call(src string, this interface{}, args ...interface{}) (Value, error) function on the Otto object itself. This is a sort of combination of Otto.Run andValue.Call. It evaluates the first argument, then if it results in a function, calls that function with the given this value and arguments.

A whole program

Let’s plug all these things together and see what we come up with!

Note: some of this will be formatted a little strangely to save space here.

package main

import (
"fmt"
"github.com/robertkrimen/otto"
) func greet(name string) {
fmt.Printf("hello, %s!\n", name)
} func main() {
vm := otto.New() if err := vm.Set("greetFromGo", greet); err != nil {
panic(err)
} // `hello, friends!`
if _, err := vm.Run(`greetFromGo('friends')`); err != nil {
panic(err)
} if _, err := vm.Run(`function greetFromJS(name) {
console.log('hello, ' + name + '!');
}`); err != nil {
panic(err)
} // `hello, friends!`
if _, err := vm.Call(`greetFromJS`, nil, "friends"); err != nil {
panic(err)
} if _, err := vm.Run("var x = 1 + 1"); err != nil {
panic(err)
} val, err := vm.Get("x")
if err != nil {
panic(err)
} v, err := val.Export()
if err != nil {
panic(err)
} // (all numbers in JavaScript are floats!)
// `float64: 2`
fmt.Printf("%T: %v\n", v, v) if _, err := vm.Run(`function add(a, b) {
return a + b;
}`); err != nil {
panic(err)
} r, err := vm.Call("add", nil, 2, 3)
if err != nil {
panic(err)
} // `5`
fmt.Printf("%s\n", r)
}

So there you have it, a whole program. It calls a Go function from JavaScript, calls a JavaScript function from Go, sets some stuff, gets some stuff, runs some code, and exports a JavaScript value to a Go value.

There’s plenty more to play around with in the otto JavaScript interpreter, and I’ll be covering some of these features in more detail, so stay tuned for more!

Back to posts

GETTING STARTED WITH THE OTTO JAVASCRIPT INTERPRETER的更多相关文章

  1. Dreamweaver 扩展开发:C-level extensibility and the JavaScript interpreter

    The C code in your library must interact with the Dreamweaver JavaScript interpreter at the followin ...

  2. Go 语言相关的优秀框架,库及软件列表

    If you see a package or project here that is no longer maintained or is not a good fit, please submi ...

  3. Awesome Go精选的Go框架,库和软件的精选清单.A curated list of awesome Go frameworks, libraries and software

    Awesome Go      financial support to Awesome Go A curated list of awesome Go frameworks, libraries a ...

  4. Dreamweaver 扩展开发: Calling a C++ function from JavaScript

    After you understand how C-level extensibility works in Dreamweaver and its dependency on certain da ...

  5. JavaScript资源大全中文版(Awesome最新版)

    Awesome系列的JavaScript资源整理.awesome-javascript是sorrycc发起维护的 JS 资源列表,内容包括:包管理器.加载器.测试框架.运行器.QA.MVC框架和库.模 ...

  6. 【repost】JavaScript Scoping and Hoisting

    JavaScript Scoping and Hoisting Do you know what value will be alerted if the following is executed ...

  7. 我所知道的Javascript

    javascript到了今天,已经不再是我10多年前所认识的小脚本了.最近我也开始用javascript编写复杂的应用,所以觉得有必要将自己的javascript知识梳理一下.同大家一起分享javas ...

  8. The Dangers of JavaScript’s Automatic Semicolon Insertion

    Although JavaScript is very powerful, the language’s fundamentals do not have a very steep learning ...

  9. 45 Useful JavaScript Tips, Tricks and Best Practices(有用的JavaScript技巧,技巧和最佳实践)

    As you know, JavaScript is the number one programming language in the world, the language of the web ...

随机推荐

  1. spring mvc介绍只试图解析(转载)

    转载路径 http://haohaoxuexi.iteye.com/blog/1770554 SpringMVC视图解析器 前言 在前一篇博客中讲了SpringMVC的Controller控制器,在这 ...

  2. Objective-C 是动态语言

    Objective-C 的动态性是由 runtime 相关的库赋予的. 当然其他语言也完全可以运行在一个 Runtime 库上而获得动态性,由于多数高级语言的诞生都对应着一种编译器,因此将编译器的特性 ...

  3. day22-类的封装、property特性以及绑定方法与非绑定方法

    目录 类的封装 两个层面的封装 第一个层面 第二个层面 封装的好处 私有模块 类的propertry特性 setter 和 deleter 类与对象的绑定方法与非绑定方法 类的封装 将类的属性或方法隐 ...

  4. ALTER OPERATOR CLASS - 修改一个操作符表的定义

    SYNOPSIS ALTER OPERATOR CLASS name USING index_method RENAME TO newname DESCRIPTION 描述 ALTER OPERATO ...

  5. python清除字符串中无用字符

    将列表val_list中包含的非法字符去掉,illegal_char是非法字符列表 def clear(): illegal_char = [' ','#','%','_','@'] tmp_list ...

  6. Java调用WebService接口实现发送手机短信验证码功能,java 手机验证码,WebService接口调用

    近来由于项目需要,需要用到手机短信验证码的功能,其中最主要的是用到了第三方提供的短信平台接口WebService客户端接口,下面我把我在项目中用到的记录一下,以便给大家提供个思路,由于本人的文采有限, ...

  7. gdb 基础

    版权:https://linuxtools-rst.readthedocs.io/zh_CN/latest/tool/gdb.html 1. gdb 调试利器 GDB是一个由GNU开源组织发布的.UN ...

  8. 中南大学2019年ACM寒假集训前期训练题集(基础题)

    先写一部分,持续到更新完. A: 寒衣调 Description 男从戎,女守家.一夜,狼烟四起,男战死沙场.从此一道黄泉,两地离别.最后,女终于在等待中老去逝去.逝去的最后是换尽一生等到的相逢和团圆 ...

  9. mysql多表合并为一张表

    有人提出要将4张表合并成一张.数据量比较大,有4千万条数据.有很多重复数据,需要对某一列进行去重. 数据量太大的话,可以看我另外一篇:http://www.cnblogs.com/magmell/p/ ...

  10. [Python3网络爬虫开发实战] 6.1-什么是Ajax

    Ajax,全称为Asynchronous JavaScript and XML,即异步的JavaScript和XML.它不是一门编程语言,而是利用JavaScript在保证页面不被刷新.页面链接不改变 ...