如何在 JavaScript 中序列化函数? [英] How can I serialize a function in JavaScript?

查看:19
本文介绍了如何在 JavaScript 中序列化函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,假设我有一个如下定义的函数:

For example, say I have a function defined as follows:

function foo() {
  return "Hello, serialized world!";
}

我希望能够序列化该函数并使用 localStorage 存储它.我该怎么做?

I want to be able to serialize that function and store it using localStorage. How can I go about doing that?

推荐答案

大多数浏览器(Chrome、Safari、Firefox,可能还有其他)从 .toString() 方法返回函数定义:

Most browsers (Chrome, Safari, Firefox, possibly others) return the definition of functions from the .toString() method:

> function foo() { return 42; }
> foo.toString()
"function foo() { return 42; }"

请小心,因为本机函数不会正确序列化.例如:

Just be careful because native functions won't serialize properly. For example:

> alert.toString()
"function alert() { [native code] }"

这篇关于如何在 JavaScript 中序列化函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆