GETTING STARTED WITH THE OTTO JAVASCRIPT INTERPRETER
原文: https://www.fknsrs.biz/blog/otto-getting-started.html.html
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 thatsetTimeout
, setInterval
, XMLHttpRequest
, fetch
, 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!
GETTING STARTED WITH THE OTTO JAVASCRIPT INTERPRETER的更多相关文章
- Dreamweaver 扩展开发:C-level extensibility and the JavaScript interpreter
The C code in your library must interact with the Dreamweaver JavaScript interpreter at the followin ...
- Go 语言相关的优秀框架,库及软件列表
If you see a package or project here that is no longer maintained or is not a good fit, please submi ...
- 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 ...
- Dreamweaver 扩展开发: Calling a C++ function from JavaScript
After you understand how C-level extensibility works in Dreamweaver and its dependency on certain da ...
- JavaScript资源大全中文版(Awesome最新版)
Awesome系列的JavaScript资源整理.awesome-javascript是sorrycc发起维护的 JS 资源列表,内容包括:包管理器.加载器.测试框架.运行器.QA.MVC框架和库.模 ...
- 【repost】JavaScript Scoping and Hoisting
JavaScript Scoping and Hoisting Do you know what value will be alerted if the following is executed ...
- 我所知道的Javascript
javascript到了今天,已经不再是我10多年前所认识的小脚本了.最近我也开始用javascript编写复杂的应用,所以觉得有必要将自己的javascript知识梳理一下.同大家一起分享javas ...
- The Dangers of JavaScript’s Automatic Semicolon Insertion
Although JavaScript is very powerful, the language’s fundamentals do not have a very steep learning ...
- 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 ...
随机推荐
- Jvisualvm--JAVA性能分析工具
JDK自带的JAVA性能分析工具.它已经在你的JDK bin目录里了,只要你使用的是JDK1.6 Update7之后的版本.点击一下jvisualvm.exe图标它就可以运行了. 这里是VisualV ...
- Node.js——require加载规则
判断require中的标识参数: 非路径的标识参数:也被称为是核心模块,已经被编译到二进制文件中 带有路径标识参数:自定义模块,一般都是相对定位 第三方模块:表现形式与核心模块一样,但是实际不一样,它 ...
- swift 语言评价
杂而不精,一团乱麻!模式乱套,不适合作为一门学习和研究语言. 谢谢 LZ 介绍,看完之后更不想用 Swift 了.从 C++那里抄个 V-Table 来很先进嘛?别跟 C++一样搞什么 STL 就好了 ...
- iOS截取特定的字符串(正则匹配)
有时候我们会有需求从一个字符串中截取其他的字符串,根据情况的不同,我们来分析几种方法~~ 一. 固定长度字符串中截取固定位置长度的字符串 // 这是比较简单的一种情况:比如截取手机号的后4位 let ...
- JAVA编程不得不看的几本经典书籍
为了帮助对java编程感兴趣的同学更好.更快的提高编程技术,武汉北大青鸟光谷校区专业老师在此推荐几本学习编程非常有用的书籍,以供大家参考. 入门类 1.<java从入门到精通>(第3版) ...
- c++ include
#include <>与#include " "区别 如果头文件名在<>中,就会被认为是标准头文件.编译器会在预定义的位置查找该头文件,如果是"& ...
- 浅谈Session的使用(原创)
目录 浅谈Session的使用(原创) 1.引言 2.Session域的生命周期 2.1 Session的创建 2.2 Session的销毁 3.那么,session被销毁后,其中存放的属性不就都访问 ...
- HDU - 4514 湫湫系列故事——设计风景线(并查集判环)
题目: 随着杭州西湖的知名度的进一步提升,园林规划专家湫湫希望设计出一条新的经典观光线路,根据老板马小腾的指示,新的风景线最好能建成环形,如果没有条件建成环形,那就建的越长越好. 现在已经勘探确定了n ...
- 零基础入门学习Python(18)--函数:灵活即强大
前言 上一节课我们基本介绍Python函数的用法,这一节课我们主要针对函数的参数进行进一步的深入学习. 知识点 形参(parameter)和实参(argument) >>> def ...
- Linux htop工具使用详解【转】
原文地址: http://www.cnphp6.com/archives/65078 一.Htop的使用简介 大家可能对top监控软件比较熟悉,今天我为大家介绍另外一个监控软件Htop,姑且称之为to ...