From 33058f2b292b3a581333bdfb21b8f671898c5060 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:40:17 -0500 Subject: initial commit --- .../mozilla/projects/crash_reporting/index.html | 47 + files/zh-cn/mozilla/projects/emscripten/index.html | 37 + files/zh-cn/mozilla/projects/index.html | 14 + files/zh-cn/mozilla/projects/l20n/index.html | 127 ++ files/zh-cn/mozilla/projects/nspr/index.html | 60 + .../mozilla/projects/nspr/reference/index.html | 770 ++++++++++ .../memory_management_operations/index.html | 424 +++++ files/zh-cn/mozilla/projects/psm/index.html | 15 + files/zh-cn/mozilla/projects/rhino/bsf/index.html | 10 + .../mozilla/projects/rhino/community/index.html | 24 + .../mozilla/projects/rhino/debugger/index.html | 220 +++ .../projects/rhino/documentation/index.html | 81 + .../projects/rhino/download_rhino/index.html | 106 ++ .../projects/rhino/embedding_tutorial/index.html | 221 +++ .../mozilla/projects/rhino/examples/index.html | 35 + files/zh-cn/mozilla/projects/rhino/index.html | 22 + .../mozilla/projects/rhino/license/index.html | 47 + .../mozilla/projects/rhino/overview/index.html | 78 + .../rhino/requirements_and_limitations/index.html | 24 + .../projects/rhino/scripting_java/index.html | 397 +++++ .../zh-cn/mozilla/projects/rhino/shell/index.html | 179 +++ files/zh-cn/mozilla/projects/social_api/index.html | 97 ++ .../mozilla/projects/social_api/share/index.html | 86 ++ .../spidermonkey/build_documentation/index.html | 294 ++++ .../comparision_of_js_engines/index.html | 105 ++ .../zh-cn/mozilla/projects/spidermonkey/index.html | 132 ++ .../spidermonkey/internals/bytecodes/index.html | 30 + .../spidermonkey/internals/functions/index.html | 73 + .../projects/spidermonkey/internals/index.html | 292 ++++ .../index.html | 382 +++++ .../index.html" | 11 + .../jsapi_reference/boolean_to_jsval/index.html | 53 + .../spidermonkey/jsapi_reference/index.html | 646 ++++++++ .../js_defineconstdoubles/index.html | 59 + .../jsapi_reference/js_doublecolon_call/index.html | 92 ++ .../js_doublecolon_ordinarytoprimitive/index.html | 66 + .../jsapi_reference/js_evaluatescript/index.html | 69 + .../jsapi_reference/js_getversion/index.html | 29 + .../jsapi_reference/js_hasownproperty/index.html | 73 + .../jsapi_reference/js_newruntime/index.html | 33 + .../jsapi_reference/js_seterrorreporter/index.html | 61 + .../jsapi_reference/js_valuetostring/index.html | 45 + .../jsapi_reference/jsclass/index.html | 137 ++ .../jsapi_reference/jsconstdoublespec/index.html | 56 + .../jsapi_reference/jserrorreport/index.html | 6 + .../jsapi_reference/jsproperty/index.html | 29 + .../jspropertydescriptor/index.html | 69 + .../jsapi_reference/jsruntime/index.html | 29 + .../projects/spidermonkey/parser_api/index.html | 1625 ++++++++++++++++++++ .../projects/spidermonkey/releases/index.html | 42 + .../projects/spidermonkey/split_object/index.html | 72 + 51 files changed, 7731 insertions(+) create mode 100644 files/zh-cn/mozilla/projects/crash_reporting/index.html create mode 100644 files/zh-cn/mozilla/projects/emscripten/index.html create mode 100644 files/zh-cn/mozilla/projects/index.html create mode 100644 files/zh-cn/mozilla/projects/l20n/index.html create mode 100644 files/zh-cn/mozilla/projects/nspr/index.html create mode 100644 files/zh-cn/mozilla/projects/nspr/reference/index.html create mode 100644 files/zh-cn/mozilla/projects/nspr/reference/memory_management_operations/index.html create mode 100644 files/zh-cn/mozilla/projects/psm/index.html create mode 100644 files/zh-cn/mozilla/projects/rhino/bsf/index.html create mode 100644 files/zh-cn/mozilla/projects/rhino/community/index.html create mode 100644 files/zh-cn/mozilla/projects/rhino/debugger/index.html create mode 100644 files/zh-cn/mozilla/projects/rhino/documentation/index.html create mode 100644 files/zh-cn/mozilla/projects/rhino/download_rhino/index.html create mode 100644 files/zh-cn/mozilla/projects/rhino/embedding_tutorial/index.html create mode 100644 files/zh-cn/mozilla/projects/rhino/examples/index.html create mode 100644 files/zh-cn/mozilla/projects/rhino/index.html create mode 100644 files/zh-cn/mozilla/projects/rhino/license/index.html create mode 100644 files/zh-cn/mozilla/projects/rhino/overview/index.html create mode 100644 files/zh-cn/mozilla/projects/rhino/requirements_and_limitations/index.html create mode 100644 files/zh-cn/mozilla/projects/rhino/scripting_java/index.html create mode 100644 files/zh-cn/mozilla/projects/rhino/shell/index.html create mode 100644 files/zh-cn/mozilla/projects/social_api/index.html create mode 100644 files/zh-cn/mozilla/projects/social_api/share/index.html create mode 100644 files/zh-cn/mozilla/projects/spidermonkey/build_documentation/index.html create mode 100644 files/zh-cn/mozilla/projects/spidermonkey/comparision_of_js_engines/index.html create mode 100644 files/zh-cn/mozilla/projects/spidermonkey/index.html create mode 100644 files/zh-cn/mozilla/projects/spidermonkey/internals/bytecodes/index.html create mode 100644 files/zh-cn/mozilla/projects/spidermonkey/internals/functions/index.html create mode 100644 files/zh-cn/mozilla/projects/spidermonkey/internals/index.html create mode 100644 files/zh-cn/mozilla/projects/spidermonkey/introduction_to_the_javascript_shell/index.html create mode 100644 "files/zh-cn/mozilla/projects/spidermonkey/javascript-c\345\274\225\346\223\216\345\265\214\345\205\245\345\274\200\345\217\221\346\214\207\345\215\227/index.html" create mode 100644 files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/boolean_to_jsval/index.html create mode 100644 files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/index.html create mode 100644 files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/js_defineconstdoubles/index.html create mode 100644 files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/js_doublecolon_call/index.html create mode 100644 files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/js_doublecolon_ordinarytoprimitive/index.html create mode 100644 files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/js_evaluatescript/index.html create mode 100644 files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/js_getversion/index.html create mode 100644 files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/js_hasownproperty/index.html create mode 100644 files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/js_newruntime/index.html create mode 100644 files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/js_seterrorreporter/index.html create mode 100644 files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/js_valuetostring/index.html create mode 100644 files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/jsclass/index.html create mode 100644 files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/jsconstdoublespec/index.html create mode 100644 files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/jserrorreport/index.html create mode 100644 files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/jsproperty/index.html create mode 100644 files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/jspropertydescriptor/index.html create mode 100644 files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/jsruntime/index.html create mode 100644 files/zh-cn/mozilla/projects/spidermonkey/parser_api/index.html create mode 100644 files/zh-cn/mozilla/projects/spidermonkey/releases/index.html create mode 100644 files/zh-cn/mozilla/projects/spidermonkey/split_object/index.html (limited to 'files/zh-cn/mozilla/projects') diff --git a/files/zh-cn/mozilla/projects/crash_reporting/index.html b/files/zh-cn/mozilla/projects/crash_reporting/index.html new file mode 100644 index 0000000000..bb8fd91519 --- /dev/null +++ b/files/zh-cn/mozilla/projects/crash_reporting/index.html @@ -0,0 +1,47 @@ +--- +title: Crash reporting +slug: Mozilla/Projects/Crash_reporting +tags: + - Crashes + - Developer Guide + - Developing Mozilla + - Firefox + - Mozilla + - NeedsTranslation + - QA + - TopicStub + - crash reports +translation_of: Mozilla/Projects/Crash_reporting +--- +

Firefox ships with an open-source crash reporting system. This system is combination of projects:

+ + + +

Where did my crash get submitted?

+ +

Crash data submitted using the Mozilla Crash Reporter is located on crash-stats. If you want to find a specific crash that you submitted, you first need to find the Crash ID that the server has assigned your crash. Type about:crashes into your location bar to get a page listing both submitted and unsubmitted crash reports. For more information, see How to get a stacktrace for a bug report.

+ +

Reports and queries

+ +

crash-stats has built-in reports of "topcrashes" for each release grouped by signature. There is also a custom query tool which allows users to limit searches on more precise information.

+ +

For more automated usage, a summary of each day's crash reports is published as a CSV file, as well as batch analysis jobs. These can be found at https://crash-analysis.mozilla.com/crash_analysis/

+ +

Finally, a set of Mozilla employees have access to directly query the underlying data in either SQL summary or using mapreduce on the storage cluster. If you are interested in obtaining this advanced access, contact Benjamin Smedberg.

+ +

See also

+ + diff --git a/files/zh-cn/mozilla/projects/emscripten/index.html b/files/zh-cn/mozilla/projects/emscripten/index.html new file mode 100644 index 0000000000..9d488c2d8e --- /dev/null +++ b/files/zh-cn/mozilla/projects/emscripten/index.html @@ -0,0 +1,37 @@ +--- +title: Emscripten +slug: Mozilla/Projects/Emscripten +translation_of: Mozilla/Projects/Emscripten +--- +

Emscripten 是一个 LLVM (底层虚拟机)生成 JavaScript 的编译器. 它采用 LLVM 的字节码 (例如,使用 Clang 从 C/C++ 或者从其他语言生成的字节码) 并将其编译成可在 Web 上面运行的 JavaScript

+ +
+

重要提示:本页简要介绍了 Emscripten 是什么。要开始使用 Emscripten请访问官方的Emscripten Wiki

+
+ +

使用 Emscripten,你可以

+ + + +

Emscripten 使原生代码可立即使用在 Web 上:是一个具有众多独立兼容的实现,可在从 PC 到 iPad 的任何地方运行的标准平台。

+ +

借助 Emscripten,C / C ++ 开发人员无需手动将代码移植到 JavaScript 上,也无需学习 JavaScript。Web 开发人员也可以从中受益,因为他们可以在自己的站点中使用成千上万的已存在的原生实用程序和库。

+ +

实际上,任何可移植的 C 或 C++ 代码库都可以通过 Emscripten 编译成 JavaScript,从需要渲染图形,播放声音,加载和处理文件的高性能游戏到诸如 Qt 的应用程序框架。

+ +

Emscripten 生成的代码(其默认输出格式为 asm.js ,这是 JavaScript 的高度优化子集)在许多情况下可以以接近原生的速度执行。

+ +
+

注意:听起来有趣吗? 阅读有关 Emscripten 的更多信息并尝试一些 demo,然后开始使用它

+
+ +

MDN上其他有趣的文章

+ + diff --git a/files/zh-cn/mozilla/projects/index.html b/files/zh-cn/mozilla/projects/index.html new file mode 100644 index 0000000000..c1e43934a2 --- /dev/null +++ b/files/zh-cn/mozilla/projects/index.html @@ -0,0 +1,14 @@ +--- +title: Projects +slug: Mozilla/Projects +tags: + - Mozilla + - NeedsContent + - NeedsTranslation + - Projects + - TopicStub +translation_of: Mozilla/Projects +--- +

{{ draft() }}

+

Below you'll find links to documentation about various Mozilla projects; these are often parts of Firefox or other products, but may also be used in other projects as well.

+

{{ LandingPageListSubpages() }}

diff --git a/files/zh-cn/mozilla/projects/l20n/index.html b/files/zh-cn/mozilla/projects/l20n/index.html new file mode 100644 index 0000000000..ce256b741f --- /dev/null +++ b/files/zh-cn/mozilla/projects/l20n/index.html @@ -0,0 +1,127 @@ +--- +title: L20n +slug: Mozilla/Projects/L20n +translation_of: Mozilla/Projects/L20n +--- +

当这个文档还是草案的时候, 请上 GitHub.

+
+ 一个JavaScript本地化框架, 释放你的本地语言的魅力, 仅使用简单的代码.
+
+
+

Introducing L20n

+

L20n reinvents software localization. Users should be able to benefit from the entire expressive power of the natural language. L20n keeps simple things simple, and at the same time makes complex things possible.

+

Through L20n, Mozilla is creating a new generation of technology that places more power in localizers' hands. L20n lets localizers reach higher levels of free linguistic expression by sharpening the divide between localization and application logic. It allows to adapt your web application not only to languages and cultures, but also contextual data, user gender and screen dimensions.

+
+
+

What L20n looks like

+

Here is a simple, straightforward example showing an English string being provided:

+
<brandName "Firefox">
+<about "About \{{ brandName }}">
+

Here is the same string being provided in Slovenian:

+
<brandName {
+  nominative: "Firefox",
+  genitive: "Firefoxa",
+  dative: "Firefoxu",
+  accusative: "Firefox",
+  locative: "Firefoxu",
+  instrumental: "Firefoxom"
+}>
+<about "O \{{ brandName.locative }}">
+
+
+

 

+
+
+

For Developers

+

Documentation for developers wanting to implement localization functionality on their web apps using L20n.

+
+
+ Internationalization for your web app
+
+ First read for developers looking to use the L20n infrastructure.
+
+ L20n's HTML bindings
+
+ Tutorial on implementing L20n in your HTML code.
+
+ L20n JavaScript API
+
+ An API for l20n.js.
+
+ L20n syntax cheatsheet for developers
+
+ A simple cheatsheet to help developers as they add L20n to their localization infrastructure.
+
+
+
+

For Localizers

+

Documentation for Localizers creating localized content for a project that uses L20n.

+
+
+ Learn the L20n syntax
+
+ How to naturally localize applications using L20n. Complete with use cases and examples of L20n in action.
+
+ Localization use-cases
+
+ How to naturally localize applications using L20n. Complete with use cases and examples of L20n in action.
+
+ L20n and Translation Memory eXchange (TMX)
+
+ How L20n impacts the Translation Memory eXchange standard for translation memory data.
+
+ L20n syntax cheatsheet for localizers
+
+ A simple cheatsheet to help localizers as they localize projects with L20n.
+
+
+
+ +

Some additional resources for developers and localizers involved with L20n.

+
+
+ L20n.org
+
+ You can try L20n live in your browser on the project page.
+
+ L20n Tinker
+
+ Test out your own L20n code in L20n Tinker.
+
+ GitHub
+
+ Where the main code for the L20n infrastructure and design spec lives.
+
+ Wiki page
+
+ Info about the project to develop L20n.
+
+
+
+ +
    +
  1. For Developers +
      +
    1. Internationalization for your web app
    2. +
    3. L20n's HTML bindings
    4. +
    5. .lol file format
    6. +
    7. L20n syntax cheatsheet for developers
    8. +
    +
  2. +
  3. For Localizers +
      +
    1. Learn the L20n syntax
    2. +
    3. Localization use cases
    4. +
    5. L20n and Translation Memory eXchange (TMX)
    6. +
    7. L20n syntax cheatsheet for localizers
    8. +
    +
  4. +
  5. Additional resources +
      +
    1. L20n.org
    2. +
    3. L20n Tinker
    4. +
    5. L20n GitHub repo
    6. +
    7. Mozilla Wiki
    8. +
    +
  6. +
diff --git a/files/zh-cn/mozilla/projects/nspr/index.html b/files/zh-cn/mozilla/projects/nspr/index.html new file mode 100644 index 0000000000..2ae2b7b9d5 --- /dev/null +++ b/files/zh-cn/mozilla/projects/nspr/index.html @@ -0,0 +1,60 @@ +--- +title: NSPR +slug: Mozilla/Projects/NSPR +translation_of: Mozilla/Projects/NSPR +--- +

Netscape Portable Runtime (NSPR)  提供一套面向系统级的与平台无关的 API  和类似于libc的函数. 这些API被用在Mozilla客户端, Red Hat公司、Sun公司的服务应用程序以及其他公司的一些软件中。

+ + + + + + + +
+

文档

+
+
+ NSPR工程页面
+
+ Contains some older technical notes and training materials. (at mozilla.org)
+
+
+
+ 关于 NSPR
+
+ This topic describes, in general terms, the goals of NSPR and a bit about how it does it.
+
+
+
+ NSPR API Reference
+
+ The reference describes each API public macro, structure and function in the NSPR API.
+
+
+
+ NSPR build instructions
+
+ How to checkout and build from source.
+
+
+
+ NSPR release process
+
+ How to prepare an NSPR release.
+
+

View All...

+
+

Community

+
    +
  • View Mozilla forums...
  • +
+

{{ DiscussionList("dev-tech-nspr", "mozilla.dev.tech.nspr") }}

+ +
+
+ Necko, NSS
+
+
+

 

+

{{ languages( { "ja": "ja/NSPR", "it": "it/NSPR" } ) }}

diff --git a/files/zh-cn/mozilla/projects/nspr/reference/index.html b/files/zh-cn/mozilla/projects/nspr/reference/index.html new file mode 100644 index 0000000000..fe690af267 --- /dev/null +++ b/files/zh-cn/mozilla/projects/nspr/reference/index.html @@ -0,0 +1,770 @@ +--- +title: NSPR API Reference +slug: Mozilla/Projects/NSPR/Reference +tags: + - NSPR + - NSPR_API_Reference + - NeedsTranslation + - TopicStub +translation_of: Mozilla/Projects/NSPR/Reference +--- + + +

Introduction to NSPR

+ + + +

NSPR Types

+ + + +

Threads

+ + + +

Process Initialization

+ + + +

Locks

+ + + +

Condition Variables

+ + + +

Monitors

+ + + +

Cached Monitors

+ + + +

I/O Types

+ + + +

I/O Functions

+ + + +

Network Addresses

+ + + +

Atomic Operations

+ + + +

Interval Timing

+ + + +

Date and Time

+ + + +

Memory Management Operations

+ + + +

String Operations

+ + + +

Floating Point Number to String Conversion

+ + + +

Long Long (64-bit) Integers

+ +

BitMaps

+ +

Formatted Printing

+ +

Linked Lists

+ + + +

Dynamic Library Linking

+ + + +

Process Management and Interprocess Communication

+ + + +

Multiwait Receive

+ +

System Information and Environment Variables

+ +

Logging

+ + + +

Instrumentation Counters

+ +

Named Shared Memory

+ + + +

Anonymous Shared Memory

+ + + +

IPC Semaphores

+ + + +

Thread Pools

+ + + +

Random Number Generator

+ + + +

Hash Tables

+ + + +

NSPR Error Handling

+ + diff --git a/files/zh-cn/mozilla/projects/nspr/reference/memory_management_operations/index.html b/files/zh-cn/mozilla/projects/nspr/reference/memory_management_operations/index.html new file mode 100644 index 0000000000..9fbb05ae70 --- /dev/null +++ b/files/zh-cn/mozilla/projects/nspr/reference/memory_management_operations/index.html @@ -0,0 +1,424 @@ +--- +title: 内存管理操作 +slug: Mozilla/Projects/NSPR/Reference/Memory_Management_Operations +tags: + - GC + - NSPR +translation_of: Mozilla/Projects/NSPR/Reference/Memory_Management_Operations +--- + + +

本章介绍用于执行内存管理的全局函数和宏。NSPR 提供基于堆内存管理的函数,映射到熟悉的malloc(), calloc(), realloc(), 和 free().

+ + + +

内存分配函数

+ +

NSPR has its own heap, and these functions act on that heap. Libraries built on top of NSPR, such as the Netscape security libraries, use these functions to allocate and free memory. If you are allocating memory for use by such libraries or freeing memory that was allocated by such libraries, you must use these NSPR functions rather than the libc equivalents.

+ +

Memory allocation functions are:

+ + + +

PR_Malloc(), PR_Calloc(), PR_Realloc(), and PR_Free() have the same signatures as their libc equivalents malloc(), calloc(), realloc(), and free(), and have the same semantics. (Note that the argument type size_t is replaced by PRUint32.) Memory allocated by PR_Malloc(), PR_Calloc(), or PR_Realloc() must be freed by PR_Free().

+ +

内存分配 Macros

+ +

Macro versions of the memory allocation functions are available, as well as additional macros that provide programming convenience:

+ + diff --git a/files/zh-cn/mozilla/projects/psm/index.html b/files/zh-cn/mozilla/projects/psm/index.html new file mode 100644 index 0000000000..69fcd93234 --- /dev/null +++ b/files/zh-cn/mozilla/projects/psm/index.html @@ -0,0 +1,15 @@ +--- +title: Personal Security Manager (PSM) +slug: Mozilla/Projects/PSM +translation_of: Mozilla/Projects/PSM +--- +

PSM全称为Personal Security Manager,包含了一套在客户应用程序上执行密码操作的代码库。这些操作包括设置SSL连接,对象签名和签名认证,证书管理(包括发行和废弃),和其它通用PKI函数。

+ +

注意:

+ + + +

 

diff --git a/files/zh-cn/mozilla/projects/rhino/bsf/index.html b/files/zh-cn/mozilla/projects/rhino/bsf/index.html new file mode 100644 index 0000000000..8cf8b6c13e --- /dev/null +++ b/files/zh-cn/mozilla/projects/rhino/bsf/index.html @@ -0,0 +1,10 @@ +--- +title: BSF +slug: Mozilla/Projects/Rhino/BSF +translation_of: Mozilla/Projects/Rhino/BSF +--- +

BSF是什么?

+

Bean Scripting Framework (BSF)起初被IBM开发,后来作为Apache Software Foundation开源代码的一部分.它为Java上的大量的脚本语言提供了一个框架,Rhino是被支持的语言之一.

+

这个框架已被大量的开源项目嵌入代码中, 包括 XSL 处理器 Xalan 和  XML/Java 构建工具 Ant. 查看 Xalan-Java Extensions 可以获取更多关于把JavaScript添加至XSL、在Apache Ant Manual中使用脚本构建项目时脚本任务的命令项的描述等信息.

+

Using BSF with Rhino

+

Now that the Apache Jakarta Bean Scripting Framework (BSF), version 2.4.0, has been officially released, you can use Rhino easily with BSF. See http://jakarta.apache.org/bsf/index.html.

diff --git a/files/zh-cn/mozilla/projects/rhino/community/index.html b/files/zh-cn/mozilla/projects/rhino/community/index.html new file mode 100644 index 0000000000..8d5c3a446c --- /dev/null +++ b/files/zh-cn/mozilla/projects/rhino/community/index.html @@ -0,0 +1,24 @@ +--- +title: Rhino社区 +slug: Mozilla/Projects/Rhino/Community +translation_of: Mozilla/Projects/Rhino/Community +--- +

是否有在Rhino文档中找不到解答的问题?下面这些资源可以给你一些帮助:

+ +

邮件列表

+ +

在Google讨论组中有一个叫mozilla-rhino的讨论组,可以讨论Rhino相关的话题.

+ +

还有一个比较老的讨论组叫mozilla.dev.tech.js-engine.rhino,已经很久没有维护了,请使用新的讨论组,但是这个老的组可能也包含一些比较有历史意义的讨论,可以去参考浏览一下.

+ +

mozilla.dev.tech.js-engine这个讨论组讨论的是关于使用C语言实现的Javascript,也有在2007年9月27日之前关于Rhino的讨论.要看在2007年9月27日之前的讨论,请移步一个叫Google group for the earlier newsgroup的Google讨论组.

+ +

Bug 系统

+ +

最好的提交Rhino bug的方式是在Rhino的Github中提交.

+ +

如果你愿意解决一些提交的Bug,我们非常欢迎您解决她,并提交一个pull请求.

+ +

许多老的Rhino的问题都被记录在Bugzilla中.也许有一些比较有历史意义的bug. 最后注意Rhino有自己的产品类目.

+ +

{{ languages( { "ja": "ja/Rhino_help" } ) }}

diff --git a/files/zh-cn/mozilla/projects/rhino/debugger/index.html b/files/zh-cn/mozilla/projects/rhino/debugger/index.html new file mode 100644 index 0000000000..8b5ab147ca --- /dev/null +++ b/files/zh-cn/mozilla/projects/rhino/debugger/index.html @@ -0,0 +1,220 @@ +--- +title: Rhino Debugger +slug: Mozilla/Projects/Rhino/Debugger +translation_of: Mozilla/Projects/Rhino/Debugger +--- +

The Rhino JavaScript debugger is a GUI that allows debugging of interpreted JavaScript scripts run in Rhino. Note that this debugger will not work with JavaScript scripts run in the mozilla browser since Rhino is not the engine used in such environments.

+

+

Current limitations:

+ +

Using the Rhino JavaScript Debugger

+

The Mozilla Rhino JavaScript engine includes a source-level debugger for debugging JavaScript scripts. The debugger is itself a Java program which you may run as

+
java org.mozilla.javascript.tools.debugger.Main [options] [filename.js] [script-arguments]
+
+
+

where the options are the same as the shell.

+

The Rhino JavaScript Debugger can debug scripts running in multiple threads and provides facilities to set and clear breakpoints, control execution, view variables, and evaluate arbitrary JavaScript code in the current scope of an executing script.

+
+
+ Console Window
+
+ The debugger redirects the System.out, System.in, and System.err streams to an internal JavaScript console window which provides an editable command line for you to enter JavaScript code and view system output. The console window maintains a history of the commands you have entered. You may move backward and forward through the history list by pressing the Up/Down arrow keys on the keyboard.
+
+ Opening Scripts
+
+ You may select the + + File->Open + menu item on the menu bar to load JavaScript scripts contained in files. This action will display a file-selection dialog box prompting you for the location of a script to load. The selected file will be compiled and displayed in a new window.
+
+ Running Scripts
+
+ You may select the + + File->Run + menu item on the menu bar to execute JavaScript scripts contained in files. This action will display a file-selection dialog box prompting you for the location of a script to execute. The loaded script will be run in a new thread and control will be given to the debugger on its first instruction.
+
+

Controlling Execution

+

The debugger provides the following facilities for you to control the execution of scripts you are debugging:

+
+
+ Step Into
+
+ To single step entering any function calls, you may do any of the following: +
    +
  • Select the + + Debug->Step Into + menu item on the menu bar
  • +
  • Press the + + Step Into + button on the toolbar
  • +
  • Press the F11 key on the keyboard
  • +
+

Execution will resume. If the current line in the script contains a function call control will return to the debugger upon entry into the function. Otherwise control will return to the debugger at the next line in the current function.

+
+
+ Step Over
+
+ To single step to the next line in the current function, you may do any of the following: +
    +
  • Select the + + Debug->Step Over + menu item on the menu bar
  • +
  • Press the + + Step Over + button on the toolbar
  • +
  • Press the F7 key on the keyboard
  • +
+

Execution will resume but control will return to the debugger at the next line in the current function or top-level script.

+
+
+ Step Out
+
+ To continue execution until the current function returns you may do any of the following: +
    +
  • Select the + + Debug->Step Out + menu item on the menu bar
  • +
  • Press the + + Step Out + button on the toolbar
  • +
  • Press the F8 key on the keyboard
  • +
+

Execution will resume until the current function returns or a breakpoint is hit.

+
+
+ Go
+
+ To resume execution of a script you may do any of the following: +
    +
  • Select the + + Debug->Go + menu item on the menu bar
  • +
  • Press the + + Go + button on the toolbar
  • +
  • Press the F5 key on the keyboard
  • +
+

Execution will resume until a breakpoint is hit or the script completes.

+
+
+ Break
+
+ To stop all running scripts and give control to the debugger you may do any of the following: +
    +
  • Select the + + Debug->Break + menu item on the menu bar
  • +
  • Press the + + Break + button on the toolbar
  • +
  • Press the Pause/Break key on the keyboard
  • +
+
+
+ Break on Exceptions
+
+ To give control to the debugger whenever a JavaScript is exception is thrown select the + + Debug->Break on Exceptions + checkbox from the menu bar. Whenever a JavaScript exception is thrown by a script a message dialog will be displayed and control will be given to the debugger at the location the exception is raised.
+
+ Break on Function Enter
+
+ Selecting + + Debug->Break on Function Enter + will give control to the debugger whenever the execution is entered into a function or script.
+
+ Break on Function Exit
+
+ Selecting + + Debug->Break on Function Return + will give control to the debugger whenever the execution is about to return from a function or script.
+
+ Moving Up and Down the Stack
+
+ The lower-left (dockable) pane in the debugger main window contains a combo-box labeled "Context:" which displays the current stack of the executing script. You may move up and down the stack by selecting an entry in the combo-box. When you select a stack frame the variables and watch windows are updated to reflect the names and values of the variables visible at that scope.
+
+ Setting and Clearing Breakpoints
+
+ The main desktop of the debugger contains file windows which display the contents of each script you are debugging. You may set a breakpoint in a script by doing one of the following: +
    +
  • Place the cursor on the line at which you want to set a breakpoint and right-click with the mouse. This action will display a pop-up menu. Select the + + Set Breakpoint + menu item.
  • +
  • Simply single-click on the line number of the line at which you want to set a breakpoint.
  • +
+

If the selected line contains executable code a red dot will appear next to the line number and a breakpoint will be set at that location.

+

You may clear breakpoint in a script by doing one of the following:

+
    +
  • Place the cursor on the line at which you want to clear a breakpoint and right-click with the mouse. This action will display a pop-up menu. Select the + + Clear Breakpoint + menu item.
  • +
  • Simply single-click on the red dot or the line number of the line at which you want to clear a breakpoint.
  • +
+

The red dot will disappear and the breakpoint at that location will be cleared.

+
+
+

Viewing Variables

+

The lower-left (dockable) pane in the debugger main window contains a tab-pane with two tabs, labeled "this" and "Locals". Each pane contains a tree-table which displays the properties of the current object and currently visible local variables, respectively.

+
+
+ This
+
+ The properties of the current object are displayed in the + + this + table. If a property is itself a JavaScript object the property may be expanded to show its sub-properties. The + + this + table is updated each time control returns to the debugger or when you change the stack location in the + + Context: + window.
+
+ Locals
+
+ The local variables of the current function are displayed in the + + Locals + table. If a variable is itself a JavaScript object the variable may be expanded to show its sub-properties. The + + Locals + table is updated each time control returns to the debugger or when you change the stack location in the + + Context: + window
+
+ Watch Window
+
+ You may enter arbitrary JavaScript expressions in the + + Watch: + table located in the lower-right (dockable) pane in the debugger main window. The expressions you enter are re-evaluated in the current scope and their current values displayed each time control returns to the debugger or when you change the stack location in the + + Context: + window.
+
+ Evaluation Window
+
+ The + + Evaluate + pane located in the lower-right (dockable) pane in the debugger main window contains an editable command line where you may enter arbitrary JavaScript code. The code is evaluated in the context of the current stack frame. The window maintains a history of the commands you have entered. You may move backward or forward through the history by pressing the Up/Down arrow keys on the keyboard.
+
diff --git a/files/zh-cn/mozilla/projects/rhino/documentation/index.html b/files/zh-cn/mozilla/projects/rhino/documentation/index.html new file mode 100644 index 0000000000..74ae49d94e --- /dev/null +++ b/files/zh-cn/mozilla/projects/rhino/documentation/index.html @@ -0,0 +1,81 @@ +--- +title: Rhino 文档 +slug: Mozilla/Projects/Rhino/Documentation +translation_of: Mozilla/Projects/Rhino/Documentation +--- +

以下是面向 Rhino 脚本创作者和集成者的信息.

+ +

概述

+ +
+
简介
+
Rhino 和 JavaScript 的简介.
+
许可
+
Rhino 的许可信息.
+
依赖和局限
+
运行 Rhino 所需要的要件; 以及 Rhino 不能做什么.
+
发布存档
+
Rhino 的历史版本以及发行说明.
+
优化
+
优化级别的详细说明.
+
FAQ
+
针对 Rhino 的 FAQ.
+
Rhino 的历史
+
关于这只野兽(Rhino)的历史.
+
+ +

撰写脚本

+ +
+
在 Java 中撰写脚本
+
使用 Rhino 编写 Java 类的方法.
+
在 Java 中撰写脚本
+
使用 Rhino 编写 Java 类的方法. (旧版).
+
性能
+
撰写更高效的 JavaScript 的窍门.
+
+ +

JavaScript 工具

+ +
+
Rhino Shell
+
交互式或批处理式执行脚本.
+
JavaScript 调试器
+
调试执行于 Rhino 中的脚本.
+
JavaScript 编译器
+
将脚本编译成类文件.
+
运行Rhino测试
+
使用Rhino运行javascript单元测试.
+
+ +

嵌入 Rhino

+ +
+
嵌入教程
+
一个介绍如何将Rhino嵌入到你的应用程序的简短教程.
+
API Javadoc Reference (无法访问?  Try this at Jarvana.)
+
一个带有解释的Rhino编程api大纲(只有一些小提示).
+
Scopes and Contexts
+
描述如何在多线程环境中高效、灵活的使用scopes和contexts.
+
序列化
+
如何在Rhino中序列化javascript对象和函数.
+
运行时
+
一个对于javascrit运行时的简短介绍.
+
Small Footprint
+
对于那些热衷于小面积脚本嵌入(small-footprint embeddings)的人的提示.
+
例子
+
一些展示如何控制javascript引擎以及创建javascript宿主对象的例子.
+
Using Rhino with Bean Scripting Framework (BSF)
+
如何在支持BSF(Bean 脚本框架)的app中通过Apache Jakarta project使用Rhino.
+
+ +

外部链接

+ +
+
在java中使用的脚本语言
+
一篇将Rhino和Jython进行对比的文章.
+
+ +

Rhino 贡献者

+ +

有志于为 Rhino 贡献力量? 来看看 Rhino Wish List 吧.

diff --git a/files/zh-cn/mozilla/projects/rhino/download_rhino/index.html b/files/zh-cn/mozilla/projects/rhino/download_rhino/index.html new file mode 100644 index 0000000000..54bf9966b8 --- /dev/null +++ b/files/zh-cn/mozilla/projects/rhino/download_rhino/index.html @@ -0,0 +1,106 @@ +--- +title: 下载 Rhino +slug: Mozilla/Projects/Rhino/Download_Rhino +translation_of: Mozilla/Projects/Rhino/Download_Rhino +--- +

Rhino 同时提供源代码和已编译形式的下载.

+ +

字节码文件

+ +

Rhino 1.7R5 是最新的稳定发行版.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
发行版本发行时间变更日志下载链接
Rhino 1.7R42012-06-18New in Rhino 1.7R4rhino1_7R4.zip
Rhino 1.7R52015-01-29变更日志rhino1_7R5.zip
Rhino 1.7.62015-04-15变更日志rhino1.7.6.zip
Rhino 1.7.72015-06-17变更日志rhino1.7.7.zip
Rhino 1.7.7.12016-02-01变更日志rhino1.7.7.1.zip
Rhino 1.7.7.22017-08-24变更日志rhino1.7.7.2.zip
Rhino 1.7.82018-01-22变更日志rhino1.7.8.zip
Rhino 1.7.92018-03-15变更日志rhino1.7.9.zip
Rhino 1.7.102018-04-09变更日志rhino1.7.10.zip
Rhino 1.7.112019-05-30变更日志rhino1.7.11.zip
Rhino 1.7.122020-01-13变更日志rhino1.7.12.zip
+ +

下载较旧版本的Rhino,可以参考 Rhino 下载存档.

+ +

许可

+ +

Rhino 是开源的, 从 1.7R4 开始以 MPL 2.0 许可.

+ +

在此之前的版本遵循 MPL 1.1/GPL 2.0 许可.

+ +

参考更详细的 Rhino 许可证 信息.

+ +

源代码

+ +

除了从上面zip文件获取源外,Rhino 的源代码可以在GitHub上的https://github.com/mozilla/rhino找到。 要获取源,使用命令

+ +
$ git clone https://github.com/mozilla/rhino.git
+
+ +

Rhino 使用 Ant 作为它的构建系统.。在Rhino分配的顶级目录运行 ant 命令将打印打印可构建目标的清单。

diff --git a/files/zh-cn/mozilla/projects/rhino/embedding_tutorial/index.html b/files/zh-cn/mozilla/projects/rhino/embedding_tutorial/index.html new file mode 100644 index 0000000000..b7cf0168f5 --- /dev/null +++ b/files/zh-cn/mozilla/projects/rhino/embedding_tutorial/index.html @@ -0,0 +1,221 @@ +--- +title: 'Tutorial: Embedding Rhino' +slug: Mozilla/Projects/Rhino/Embedding_tutorial +translation_of: Mozilla/Projects/Rhino/Embedding_tutorial +--- +

Embedding Rhino can be done simply with good results. With more effort on the part of the embedder, the objects exposed to scripts can be customized further.

+

This tutorial leads you through the steps from a simple embedding to more customized, complex embeddings. Fully compilable examples are provided along the way.

+

The examples live in the rhino/examples directory in the distribution and in mozilla/js/rhino/examples in cvs. This document will link to them using lxr.

+

In this document, JavaScript code will be in green, Java code will be in green, and shell logs will be in purple.

+

In this document:

+ +

RunScript: A simple embedding

+

About the simplest embedding of Rhino possible is the RunScript example. All it does it read a script from the command line, execute it, and print a result.

+

Here's an example use of RunScript from a shell command line:

+
$ java RunScript "Math.cos(Math.PI)"
+-1
+$ java RunScript "function f(x){return x+1} f(7)"
+8
+
+

Note that you'll have to have both the Rhino classes and the RunScript example class file in the classpath. Let's step through the body of main one line at time.

+

Entering a Context

+

The code

+
Context cx = Context.enter();
+
+

Creates and enters a Context. A Context stores information about the execution environment of a script.

+

Initializing standard objects

+

The code

+
Scriptable scope = cx.initStandardObjects();
+
+

Initializes the standard objects (Object, Function, etc.) This must be done before scripts can be executed. The null parameter tells initStandardObjects to create and return a scope object that we use in later calls.

+

Collecting the arguments

+

This code is standard Java and not specific to Rhino. It just collects all the arguments and concatenates them together.

+
String s = "";
+for (int i=0; i < args.length; i++) {
+    s += args[i];
+}
+
+

Evaluating a script

+

The code

+
Object result = cx.evaluateString(scope, s, "<cmd>", 1, null);
+
+

uses the Context cx to evaluate a string. Evaluation of the script looks up variables in scope, and errors will be reported with the filename <cmd> and line number 1.

+

Printing the result

+

The code

+
System.out.println(cx.toString(result));
+
+

prints the result of evaluating the script (contained in the variable result). result could be a string, JavaScript object, or other values. The toString method converts any JavaScript value to a string.

+

Exiting the Context

+

The code

+
} finally {
+    Context.exit();
+}
+
+

exits the Context. This removes the association between the Context and the current thread and is an essential cleanup action. There should be a call to exit for every call to enter. To make sure that it is called even if an exception is thrown, it is put into the finally block corresponding to the try block starting after Context.enter().

+

Expose Java APIs

+

Using Java APIs

+

No additional code in the embedding needed! The JavaScript feature called + + LiveConnect + allows JavaScript programs to interact with Java objects:

+
$ java RunScript "java.lang.System.out.println(3)"
+3.0
+undefined
+
+

Implementing interfaces

+

Using Rhino, JavaScript objects can implement arbitrary Java interfaces. There's no Java code to write -- it's part of Rhino's LiveConnect implementation. For example, we can see how to implement java.lang.Runnable in a Rhino shell session:

+
js> obj = { run: function() { print("hi"); } }
+[object Object]
+js> obj.run()
+hi
+js> r = new java.lang.Runnable(obj);
+[object Object]
+js> t = new java.lang.Thread(r)
+Thread[Thread-0,5,main]
+js> t.start()
+hi
+
+

Adding Java objects

+

The next example is RunScript2. This is the same as RunScript, but with the addition of two extra lines of code:

+
Object wrappedOut = Context.javaToJS(System.out, scope);
+ScriptableObject.putProperty(scope, "out", wrappedOut);
+
+

These lines add a global variable out that is a JavaScript reflection of the System.out variable:

+
$ java RunScript2 "out.println(42)"
+42.0
+undefined
+
+

Using JavaScript objects from Java

+

After evaluating a script it's possible to query the scope for variables and functions, extracting values and calling JavaScript functions. This is illustrated in the RunScript3 example. This example adds the ability to print the value of variable x and the result of calling function f. Both x and f are expected to be defined by the evaluated script. For example,

+
$ java RunScript3 "x = 7"
+x = 7
+f is undefined or not a function.
+$ java RunScript3 "function f(a) { return a; }"
+x is not defined.
+f("my args") = my arg
+
+

Using JavaScript variables

+

To print out the value of x, we add the following code:

+
Object x = scope.get("x", scope);
+if (x == Scriptable.NOT_FOUND) {
+    System.out.println("x is not defined.");
+} else {
+    System.out.println("x = " + Context.toString(x));
+}
+
+

Calling JavaScript functions

+

To get the function f, call it, and print the result, we add this code:

+
Object fObj = scope.get("f", scope);
+if (!(fObj instanceof Function)) {
+    System.out.println("f is undefined or not a function.");
+} else {
+    Object functionArgs[] = { "my arg" };
+    Function f = (Function)fObj;
+    Object result = f.call(cx, scope, scope, functionArgs);
+    String report = "f('my args') = " + Context.toString(result);
+    System.out.println(report);
+}
+
+

JavaScript host objects

+

Defining Host Objects

+

Custom host objects can implement special JavaScript features like dynamic properties.

+

Counter example

+

The Counter example is a simple host object. We'll go through it method by method below.

+

It's easy to try out new host object classes in the shell using its built-in defineClass function. We'll see how to add it to RunScript later. (Note that because the java -jar option preempts the rest of the classpath, we can't use that and access the Counter class.)

+
$ java -cp "js.jar;examples" org.mozilla.javascript.tools.shell.Main
+js> defineClass("Counter")
+js> c = new Counter(7)
+[object Counter]
+js> c.count
+7
+js> c.count
+8
+js> c.count
+9
+js> c.resetCount()
+js> c.count
+0
+
+

Counter's constructors

+

The zero-argument constructor is used by Rhino runtime to create instances. For the counter example, no initialization work is needed, so the implementation is empty.

+
public Counter () { }
+
+

The method jsConstructor defines the JavaScript constructor that was called with the expression new Counter(7) in the JavaScript code above.

+
public void jsConstructor(int a) { count
+= a; }
+
+

Class name

+

The class name is defined by the getClassName method. This is used to determine the name of the constructor.

+
public String getClassName() { return "Counter";
+}
+
+

Dynamic properties

+

Dynamic properties are defined by methods beginning with jsGet_ or jsSet_. The method jsGet_count defines the + + count + property.

+
public int jsGet_count() { return count++;
+}
+
+

The expression c.count in the JavaScript code above results in a call to this method.

+

Defining JavaScript "methods"

+

Methods can be defined using the jsFunction_ prefix. Here we define resetCount for JavaScript.

+
public void jsFunction_resetCount() { count
+= 0; }
+
+

The call c.resetCount() above calls this method.

+

Adding Counter to RunScript

+

Now take a look at the RunScript4 example. It's the same as RunScript except for two additions. The method ScriptableObject.defineClass uses a Java class to define the Counter "class" in the top-level scope:

+
ScriptableObject.defineClass(scope, Counter.class);
+
+

Now we can reference the Counter object from our script:

+
$ java RunScript4 "c = new Counter(3); c.count;
+c.count;"
+
+

It also creates a new instance of the Counter object from within our Java code, constructing it with the value 7, and assigning it to the top-level variable myCounter:

+
Object[] arg = { new Integer(7) };
+Scriptable myCounter = cx.newObject(scope, "Counter", arg);
+scope.put("myCounter", scope, myCounter);
+
+

Now we can reference the myCounter object from our script:

+
$ java RunScript3 'RunScript4 'myCounter.count; myCounter.count'
+8
+
diff --git a/files/zh-cn/mozilla/projects/rhino/examples/index.html b/files/zh-cn/mozilla/projects/rhino/examples/index.html new file mode 100644 index 0000000000..087697b94a --- /dev/null +++ b/files/zh-cn/mozilla/projects/rhino/examples/index.html @@ -0,0 +1,35 @@ +--- +title: Rhino Examples +slug: Mozilla/Projects/Rhino/Examples +translation_of: Mozilla/Projects/Rhino/Examples +--- +
+  
+

+

Examples have been provided that show how to control the JavaScript engine and how  to implement scriptable host objects. All the examples are in the git tree at mozilla/js/rhino/examples.

+

Sample Scripts

+

The unique.js script allows printing unique lines from a file.

+

The liveConnect.js script shows a sample usage of LiveConnect (Java-to-JavaScript connectivity).

+

The jsdoc.js script is a JavaScript analog to Java's javadoc. It makes heavy use of regular expressions.

+

The checkParam.js script is a useful tool to check that @param tags in Java documentation comments match the parameters in the corresponding Java method.

+

The enum.js script is a good example of using a JavaAdapter to implement a Java interface using a JavaScript object.

+

The NervousText.js script is a JavaScript implementation of the famous NervousText applet using JavaScript compiled to Java classes using jsc. It can be run in the HTML page NervousText.html.

+

Controlling the JavaScript Engine

+

The RunScript class

+

RunScript.java is a simple program that executes a script from the command line.

+

The Control class

+

Control.java is a program that executes a simple script and then manipulates the result.

+

JavaScript Shell

+

Shell.java is a program that executes JavaScript programs; it is a simplified version of the shell in the tools package. The programs may be specified as files on the command line or by typing interactively while the shell is running.

+

PrimitiveWrapFactory

+

PrimitiveWrapFactory.java is an example of a WrapFactory that can be used to control the wrapping behavior of the Rhino engine on calls to Java methods.

+

Multithreaded Script Execution

+

DynamicScopes.java is a program that creates a single global scope object and then shares it across multiple threads. Sharing the global scope allows both information to be shared across threads, and amortizes the cost of Context.initStandardObjects by only performing that expensive operation once.

+

Implementing Host Objects

+

First check out the tutorial if you haven't already.

+

The Foo class - Extending ScriptableObject

+

Foo.java is a simple JavaScript host object that includes a property with an associated action and a variable argument method.

+

The Matrix class - Implementing Scriptable

+

Matrix.java provides a simple multidimensional array by implementing the Scriptable interface.

+

The File class - An advanced example

+

File.java extends ScriptableObject to provide a means of reading and writing files from JavaScript. A more involved example of host object definition.

diff --git a/files/zh-cn/mozilla/projects/rhino/index.html b/files/zh-cn/mozilla/projects/rhino/index.html new file mode 100644 index 0000000000..86818aa172 --- /dev/null +++ b/files/zh-cn/mozilla/projects/rhino/index.html @@ -0,0 +1,22 @@ +--- +title: Rhino +slug: Mozilla/Projects/Rhino +translation_of: Mozilla/Projects/Rhino +--- +

Image:rhino.jpg

+ +

Rhino 是一个完全使用Java语言编写的开源JavaScript实现。Rhino通常用于在Java程序中,为最终用户提供脚本化能力。它被作为J2SE 6上的默认Java脚本化引擎。

+ +

Rhino 下载

+ +

如何 获取源码和二进制文件

+ +

Rhino 文档

+ +

为脚本编写者和嵌入者提供的 一些Rhino信息.

+ +

Rhino 帮助

+ +

如果你被卡住了,可以参考 这里的一些资源.

+ +

{{ languages( { "zh-cn": "zh-cn/Rhino" } ) }}

diff --git a/files/zh-cn/mozilla/projects/rhino/license/index.html b/files/zh-cn/mozilla/projects/rhino/license/index.html new file mode 100644 index 0000000000..035688ed65 --- /dev/null +++ b/files/zh-cn/mozilla/projects/rhino/license/index.html @@ -0,0 +1,47 @@ +--- +title: Rhino license +slug: Mozilla/Projects/Rhino/License +translation_of: Mozilla/Projects/Rhino/License +--- +

Rhino is available under open source licenses.

+ +

MPL/GPL License

+ +

The majority of the source code for Rhino is available under a MPL 1.1/GPL 2.0 license.

+ +

License for portions of the Rhino debugger

+ +

Additionally, some files (currently the contents of toolsrc/org/mozilla/javascript/tools/debugger/treetable/) are available under the following license:

+ +
 * Copyright 1997, 1998 Sun Microsystems, Inc.  All Rights Reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ *   - Redistributions of source code must retain the above copyright
+ *     notice, this list of conditions and the following disclaimer.
+ *
+ *   - Redistributions in binary form must reproduce the above copyright
+ *     notice, this list of conditions and the following disclaimer in the
+ *     documentation and/or other materials provided with the distribution.
+ *
+ *   - Neither the name of Sun Microsystems nor the names of its
+ *     contributors may be used to endorse or promote products derived
+ *     from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
+ * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ +
+

Norrisboyd 06:16, 14 April 2008 (PDT)

diff --git a/files/zh-cn/mozilla/projects/rhino/overview/index.html b/files/zh-cn/mozilla/projects/rhino/overview/index.html new file mode 100644 index 0000000000..ba6a9aaa18 --- /dev/null +++ b/files/zh-cn/mozilla/projects/rhino/overview/index.html @@ -0,0 +1,78 @@ +--- +title: Rhino overview +slug: Mozilla/Projects/Rhino/Overview +translation_of: Mozilla/Projects/Rhino/Overview +--- +

简介

+ +

大多数用过 JavaScript 的人都是将js脚本放入HTML页面中使用。然而, Rhino 仅仅是对javascript核心部分的实现,并没有包含操作HTML的对象或方法。

+ +

Rhino 包括

+ + + +

语言

+ +

JavaScript 的标准是 Standard ECMA-262 ECMAScript: A general purpose, cross-platform programming language. Rhino 1.3 及以上版本遵照上述标准的第3版。

+ +

Rhino 1.6 及以上版本实现了 ECMA-357 ECMAScript for XML (E4X) 标准. 查看详细的规格说明可以获得更多的信息,查看 Rhino version 1.6R1 release notes 可以看到Rhino对标准实现的具体情况。

+ +

此外,Rhino实现了JavaAdapters,这样我们可以用一个JavaScript对象来实现任何java的接口或者继承任何java的类。查看下载文件中example文件夹中的enum.js获取更多的信息。.

+ +

有很多JavaScript的书和教程。 我们推荐JavaScript: The Definitive Guide 这本书,里面有一章是说Rhino的。

+ +

废弃的语言特性

+ +

很多在JavaScript 1.2中定义的特性已经被废弃了. 这些特性允许“计算反射”:可以决定和影响它被评价方法等方面的能力。 这些特性没有被广泛使用,他们对阻碍和防止优化的行为强加了重要的约束。 这些被废弃的特性是 __proto__ 和 __parent__ 属性, 还有构造函数 With,、ClosureCall。在JavaScript 1.4中使用这些特性会产生错误。在其他的版本中使用这些特性,会产生警告。

+ +

国际化

+ +

The messages reported by the JavaScript engine are by default retrieved from the property file org/mozilla/javascript/resources/Messages.properties. If other properties files with extensions corresponding to the current locale exist, they will be used instead.

+ +

JavaScript语言版本

+ +

JavaScript引擎的很多行为与语言的版本有关。在浏览器调用中,JavaScript版本的选择是通过script标签中的LANGUAGE属性定义的,比如"JavaScript1.2"。

+ +

1.3 和更高版本是ECMA一致的。

+ +

操作符 ==  和 !=

+ +

1.2版本用 == 和 != 来处理绝对相等的问题。 在1.3或更高的版本里, == 和 != 和ECMA中所描述的一样。 操作符 === and !== 在所有版本中都表示绝对相等。

+ +

布尔转换

+ +

1.3之前的所有版本Boolean(new Boolean(false)) 值为false 。在1.3及1.3之后,它的值为true。

+ +

Array.prototype.toString 和 Object.prototype.toString

+ +

1.2版本只是返回数组或对象的文字符号 (比如"{{ mediawiki.external(1,2,3) }}" or "{a:1, b:2}" )。 在1.3或更高版本中这些函数与ECMA标准一致。

+ +

Array 构造函数

+ +

只有在1.2版本中,Array(i) 用一个参数i构造一个只有一个元素且元素的值为i的数组。 在其他版本中,使用和ECMA一致的标准 (一个没有元素的数组被构造,长度为i)。

+ +

String.prototype.substring

+ +

只有在1.2版本中, 如果第一个参数小于第二个参数,两个参数不会互换。其他的版本都符合ECMA标准。

+ +

String.prototype.split

+ +

只有对1.2版本,split按照Perl4的特例当用一个单独的空格字符作参数时, (跳过最先的空白,用空白分割). 其他的版本完全按照ECMA的标准分割。

+ +

安全

+ +

Rhino的安全特性提供了找到代码片段的来源的功能 (还有任何会轮流产生的代码片段)。这些特性考虑到了传统的基于URL的安全策略(在网景领航员中的JavaScript)的实现。执行信任的JavaScript代码时可以不考虑安全性特征。

+ +

运行不被信任的JavaScript代码时,需要做两件事来保证安全性。第一,每一个被创建的Context必须被提供一个实现SecuritySupport接口的实例。 这样在功能上给Rhino提供了让它执行安全相关任务的支持。

+ +

第二, security.requireSecurityDomain属性的值应该被改为true在资源束bundle org.mozilla.javascript.resources.Security中. 这个属性的值可以在运行时通过调用ContextisSecurityDomainRequired方法来决定。将这个属性设置为ture,要求任何编译或评估JavaScript的调用必须提供一个安全区域对象(任意类型),用来标识JavaScript代码。在一个典型的客户端嵌入中,这个对象可能是提供javascript的服务器的URL,或者是一个包含代码片段的签发人的代表(用于基于证书的安全策略)。

+ +

当JavaScript代码想要执行一个受限制的行为时,安全区域会被后面的方法检索。类上下文会从安全管理(java.lang.SecurityManager.getClassContext())中得到。执行限制行为的代码对应的类 可以通过寻找一个在类上下文中合适的位置得到。如果调用者是JavaScript,得到的类可能是一种或两种类型。首先,它可能是解释器(如果解释器模式有效)。第二,它有可能是一个生成的类,如果类文件生成支持。一个植入可以区分两种情况,通过调用在Context Class中调用isInterpreterClass()。 如果是解释器类,调用Context的getInterpreterSecurityDomain() 方法来获取当前正在执行的被解释的脚本或方法的安全区域。否则,就是一个生成的类,一个嵌入可以调用在实现SecuritySupport的类中调用getSecurityDomain()。当类被定义而且被打开,恰当的安全区域和它建立关联,而且可以通过调用这个方法找回。一旦安全区域被决定,一个植入可以执行任何检查者适合去决定是否允许去做的操作。

+ +

{{ languages( { "ja": "ja/Rhino_Overview" } ) }}

diff --git a/files/zh-cn/mozilla/projects/rhino/requirements_and_limitations/index.html b/files/zh-cn/mozilla/projects/rhino/requirements_and_limitations/index.html new file mode 100644 index 0000000000..8a159ae843 --- /dev/null +++ b/files/zh-cn/mozilla/projects/rhino/requirements_and_limitations/index.html @@ -0,0 +1,24 @@ +--- +title: Rhino requirements and limitations +slug: Mozilla/Projects/Rhino/Requirements_and_Limitations +translation_of: Mozilla/Projects/Rhino/Requirements_and_Limitations +--- +

Requirements

+

Recent versions of Rhino have only been tested with JDK 1.4 and greater. Older versions support JDKs as early as 1.1.

+

To use the JavaAdapter feature or an optimization level of 0 or greater, Rhino must be running under a security manager that allows the definition of class loaders.

+

Limitations

+

LiveConnect

+

If a JavaObject's field's name collides with that of a method, the value of that field is retrieved lazily, and can be counter-intuitively affected by later assignments:

+
javaObj.fieldAndMethod = 5;
+var field = javaObj.fieldAndMethod;
+javaObj.fieldAndMethod = 7;
+// now, field == 7
+
+

You can work around this by forcing the field value to be converted to a JavaScript type when you take its value:

+
javaObj.fieldAndMethod = 5;
+var field = javaObj.fieldAndMethod + 0; // force conversion now
+javaObj.fieldAndMethod = 7;
+// now, field == 5
+
+

JSObject

+

Rhino does NOT support the netscape.javascript.JSObject class.

diff --git a/files/zh-cn/mozilla/projects/rhino/scripting_java/index.html b/files/zh-cn/mozilla/projects/rhino/scripting_java/index.html new file mode 100644 index 0000000000..013ad3aa89 --- /dev/null +++ b/files/zh-cn/mozilla/projects/rhino/scripting_java/index.html @@ -0,0 +1,397 @@ +--- +title: Scripting Java +slug: Mozilla/Projects/Rhino/Scripting_Java +translation_of: Mozilla/Projects/Rhino/Scripting_Java +--- +

这篇文章描述了如何在rhino中使用java。使用脚本调用Java有很多用途,它使得我们可以利用Java中现有的库,来帮助我们构建强大的脚本。我们可以通过编写脚本,来对Java程序进行测试。可以通过脚本来进行探索式编程,辅助Java的开发,所谓探索式编程,就是通过快速地编程调用库或API来探索这些库或API可以做什么,显而易见,脚本语言很适合探索式编程。

+ +

这里注意,ECMA标准并没有包含和Java(或者其他任何对象系统)交互的标准。本文所描述的所有内容,应该被认为是一个扩展。

+ + + +

访问 Java Packages 和 Classes

+ +

Java的每段代码都是类的一部分,每一个JAVA类都是包的一部分。在Javascript中,脚本不属于任何package。我们可以访问Java包中的类么?

+ +

Rhino定义了一个顶层的变量Packages。Packages的所有属性都是Java中顶层的包,比如java和com。比如我们可以访问java包:

+ +
js> Packages.java
+[JavaPackage java]
+ +

还有一种更方便的方式,Rhino定义了一个顶层的变量java,等价于Packages.java。所以上面的例子可以更简介地写成:

+ +
js> java
+[JavaPackage java]
+
+ +

我们可以通过访问包的下层,来直接访问java类:

+ +
js> java.io.File
+[JavaClass java.io.File]
+
+ +

如果你的脚本需要访问很多的Java类,每次都附带完整的包名会使得编程很麻烦。Rhino提供了一个顶层的方法importPackage,它的功能和Java的import一样。比如,我们可以导入java.io包中的所有类,然后直接通过类名File来访问java.io.File:

+ +
js> importPackage(java.io)
+js> File
+[JavaClass java.io.File]
+
+ +

这里importPackage(java.io)使得java.io包中的所有类(例如File)可以在顶层被访问。这和Java中的java.io.*;等价。

+ +

要注意Java会暗中导入java.lang.*,但是Rhino不会。因为JavaScript的顶层对象Boolean、Math、Number、Object和String和java.lang包中同名的类并不相同。因为这种冲突,建议不要用importPackage来导入java.lang包。

+ +

有一点要注意的,就是Rhino对于指定包名或类名时是如何处理错误的。如果java.Myclass是可访问的,Rhino会试图加载名为java.MyClass的类,如果加载失败,它会假设java.MyClass是一个包名,不会报错:

+ +
js> java.MyClass
+[JavaPackage java.MyClass]
+
+ +

只有在你试图将这个对象当作类使用时,才会报错。

+ +

额外的包和类

+ +

额外的包和类也可以在Rhino中使用。确认你的.jar或.class文件在你的classpath里,你就可以在你的JavaScript应用中导入它们。这些包基本不会在java包中,所以你在使用时,需要在包前加上前缀"Packages"。 比如你想导入 org.mozilla.javascript 包,你应该像下面这样去使用importPackage():

+ +
$ java org.mozilla.javascript.tools.shell.Main
+js> importPackage(Packages.org.mozilla.javascript);
+js> Context.currentContext;
+org.mozilla.javascript.Context@bb6ab6
+
+ +

偶尔,我们也会见到在一些例子中使用包的完整名称,而没有使用importPackage()。这也是可以的,只是会让你多打一些字。如果使用完整的名称,上面的例子就会变成下面这样:

+ +
$ java org.mozilla.javascript.tools.shell.Main
+js> jsPackage = Packages.org.mozilla.javascript;
+[JavaPackage org.mozilla.javascript]
+js> jsPackage.Context.currentContext;
+org.mozilla.javascript.Context@bb6ab6
+
+ +

同样,你可以通过importClass()来导入一个类,上面的例子也可以像这样写:

+ +
$ java org.mozilla.javascript.tools.shell.Main
+js> importClass(Packages.org.mozilla.javascript.Context);
+js>  Context.currentContext;
+org.mozilla.javascript.Context@bb6ab6
+ +

和Java一起工作

+ +

现在我们可以访问Java类,下一步就是要创建一个对象。方法就和在Java中一样, 用new来创建对象:

+ +
js> new java.util.Date()
+Thu Jan 24 16:18:17 EST 2002
+
+ +

如果我们将创建的对象存放在JavaScript变量中,我们可以调用它的方法:

+ +
js> f = new java.io.File("test.txt")
+test.txt
+js> f.exists()
+true
+js> f.getName()
+test.txt
+
+ +

静态方法和属性可以直接通过类对象来访问:

+ +
js> java.lang.Math.PI
+3.141592653589793
+js> java.lang.Math.cos(0)
+1
+
+ +

不像Java,在JavaScript里,方法就是一个对象。它可以被评估,也可以被调用。如果我们去查看这个方法,我们可以看到这个方法所有重载的形式:

+ +
js> f.listFiles
+function listFiles() {/*
+java.io.File[] listFiles()
+java.io.File[] listFiles(java.io.FilenameFilter)
+java.io.File[] listFiles(java.io.FileFilter)
+*/}
+
+ +

输出告诉我们,File类有listFiles方法的三种重载:一种不包含参数的,另一种包含一个FilenameFilter类型的参数,第三个包含一个FileFilter类型的参数。所有的方法都返回一个File对象数组。可以观察到Java方法的参数和返回类型在探索式编程中是非常有用的,尤其是在对一个方法的参数和返回对象不确定的时候。

+ +

另一个有助于探索式编程的特性,是可以看到对象中定义的所有方法和属性。用JavaScript的for..in , 我们可以打印这些值:

+ +
js> for (i in f) { print(i) }
+exists
+parentFile
+mkdir
+toString
+wait
+[44 others]
+
+ +

注意这里不仅列出了File类中的所有方法,也列出了从基类java.lang.Object中继承的方法,例如wait。这使得我们可以更好地处理那些有复杂继承关系的对象,因为我们可以看到对象中所有可用的方法。

+ +

Rhino可以通过属性名来方便地访问JavaBean的属性。一个JavaBean的属性foo被方法getFoo和setFoo定义,另外,一个也叫foo的boolean类型的属性,可以被isFoo来定义。比如, 下面的代码实际上调用了File对象的getName和isDirectory方法。

+ +
js> f.name
+test.txt
+js> f.directory
+false
+
+ +

调用重载方法

+ +

 根据参数类型选择调用方法的过程称为重载决议。在 Java 中, 重载决议在编译时执行, 而在rhino中则在运行时发生。这种差异是不可避免的, 因为 JavaScript 使用动态类型, 在2章中: 由于变量的类型直到运行时才知道, 才会发生重载决议。

+ +
+
例如, 请查看下面的 Java 类, 它定义了许多重载方法并调用它们。 
+
+ + + +
public class Overload {
+
+    public String f(Object o) { return "f(Object)"; }
+    public String f(String s) { return "f(String)"; }
+    public String f(int i)    { return "f(int)"; }
+
+    public String g(String s, int i) { return "g(String,int)"; }
+    public String g(int i, String s) { return "g(int,String)"; }
+
+    public static void main(String[] args) {
+        Overload o = new Overload();
+        Object[] a = new Object[] { new Integer(3), "hi", Overload.class };
+        for (int i = 0; i != a.length; ++i)
+            System.out.println(o.f(a[i]));
+    }
+}
+
+ +

当我们编译和执行程序, 它产生输出

+ +
f(Object)
+f(Object)
+f(Object)
+
+ +

但是, 如果我们编写一个类似的脚本

+ +
var o = new Packages.Overload();
+var a = [ 3, "hi", Packages.Overload ];
+for (var i = 0; i != a.length; ++i)
+    print(o.f(a[i]));
+
+ +

并且运行它,将会输出

+ +
f(int)
+f(String)
+f(Object)
+
+ +

因为Rhino在运行时选择重载方法, 所以它会调用与该参数匹配的更具体的类型。 同时, 在编译时, Java 只在参数的类型上选择重载方法。

+ +

尽管这有利于选择一种方法,这种方法可能是每个调用的更好匹配,但它确实对性能有影响,因为每次调用时都要做更多的工作。事实上,这种性能代价在实际应用中并不明显。

+ +

因为重载决议发生在运行时,它可能在运行时失败。例如,如果我们用两个整数调用重载方法g,我们就会得到一个错误,因为方法的两个形式都比另一个更接近参数类型:

+ +
js> o.g(3,4)
+js:"<stdin>", line 2: The choice of Java method Overload.g
+matching JavaScript argument types (number,number) is ambiguous;
+candidate methods are:
+class java.lang.String g(java.lang.String,int)
+class java.lang.String g(int,java.lang.String)
+
+ +

http://www.mozilla.org/js/liveconnect/lc3_method_overloading.html 提供了一个更精确的重载语义定义

+ +

  实现Java接口

+ + + +

现在我们可以访问Java类,创建Java对象,并访问这些对象的字段、方法和属性,我们就可以轻松掌握大量的功能。但是,在少数情况下是不够用的:Java中的很多API通过提供客户端必须实现的接口来工作。其中一个例子就是Thread类:其构造函数Runnable包含一个run方法,这个方法在新线程启动时被调用。

+ +

为了满足这种需求,Rhino提供了创建新的Java对象实现的接口的能力。首先,我们必须定义一个JavaScript对象,其中的函数属性的名称与Java接口所需的方法名称相匹配。要实现一个Runnable ,我们只需要定义一个不带参数的run单方法。如果你还记得第3章,可以用{ propertyName: value}符号定义一个JavaScript对象。我们可以在这里结合函数表达式使用这个语法来用一个 run方法定义一个JavaScript对象:

+ +
js> obj = { run: function () { print("\nrunning"); } }
+[object Object]
+js> obj.run()
+
+running
+
+ + + +

现在我们可以通过构建一个 Runnable 来实现 Runnable 接口的对象:

+ +
js> r = new java.lang.Runnable(obj);
+ + + +
js> r = new java.lang.Runnable(obj);
+[object JavaObject]
+
+ +

在Java中,不可能在接口上使用new运算符,因为没有可用的实现。Rhino从JavaScript对象中获取实现obj现在我们有一个对象实现Runnable,我们可以创建Thread并运行它。我们定义的函数run 将在新线程上调用。

+ +
js> t = new java.lang.Thread(r)
+Thread[Thread-2,5,main]
+js> t.start()
+js>
+
+running
+
+ + + +

最终js提示和新线程的输出可能以任意顺序显示,具体取决于线程调度。

+ +

在后台,Rhino为一个新的Java类生成字节码,该类实现 Runnable 并转发对其 run方法的所有调用,并转发给关联的JavaScript对象。实现此类的对象称为Java适配器。因为转发到JavaScript是在运行时发生的,所以可能会延迟定义实现接口的方法直到它们被调用。虽然省略必要的方法对大编程来说是一种糟糕的做法,但它对小脚本和探索性编程很有用。

+ + + +

JavaAdapter构造函数

+ +

在前面的章节中,我们使用 new 运算符与Java接口创建Java适配器。这种方法有其局限性:不可能实现多个接口,也不能扩展非抽象类。因为这些原因,有一个 JavaAdapter 构造函数。

+ +

JavaAdapter构造函数的语法是:

+ +
new JavaAdapter(javaIntfOrClass, [javaIntf, ..., javaIntf,] javascriptObject)
+
+ +

这里javaIntfOrClass是一个实现的接口或一个扩展的类,并且javaIntf是实现接口的接口。而javascriptObject 则包含从Java适配器调用的方法的JavaScript对象。

+ +

在实践中,几乎不需要JavaAdapter 直接调用构造函数。大多数情况下,使用new运算符之前的语法就足够了。

+ +

作为Java接口的JavaScript函数

+ +

通常我们只需要使用一种方法实现一个接口,就像前面的 Runnable 例子或者提供各种事件监听器实现一样。为了方便这个,Rhino允许在这种接口传递JavaScript函数。该函数被称为接口方法的实现。

+ +

这里是简化的 Runnable 实例:

+ +
js> t = java.lang.Thread(function () { print("\nrunning"); });
+Thread[Thread-0,5,main]
+js> t.start()
+js>
+running
+
+ +

如果所有的方法都具有相同的签名,Rhino还允许使用JavaScript函数作为Java接口的实现方法。当调用函数时,Rhino将方法的名称作为附加参数传递。函数可以使用它来代表被调用的方法:

+ +
js> var frame = new Packages.javax.swing.JFrame();
+js> frame.addWindowListener(function(event, methodName) {
+	if (methodName == "windowClosing") {
+            print("Calling System.exit()..."); java.lang.System.exit(0);
+	}
+    });
+js> frame.setSize(100, 100);
+js> frame.visible = true;
+true
+js> Calling System.exit()...
+
+ +

创建Java数组

+ +

Rhino不提供创建Java数组的特殊语法。你必须使用这个 java.lang.reflect.Array 类来达到这个目的。要创建一个由五个Java字符串组成的数组,可以进行以下调用:

+ +
js> a = java.lang.reflect.Array.newInstance(java.lang.String, 5);
+[Ljava.lang.String;@7ffe01
+
+ +

要创建一个基本类型数组,我们必须使用 java.lang 包中相关对象类中定义的特殊TYPE字段。例如,要创建一个字节数组,我们必须使用特殊字段 java.lang.Byte.TYPE:

+ +
js> a = java.lang.reflect.Array.newInstance(java.lang.Character.TYPE, 2);
+[C@7a84e4
+
+ +

而且结果值是允许被使用在该类型的Java数组的任何地方。

+ +
js> a[0] = 104
+104
+js> a[1] = 105
+105
+js> new java.lang.String(a)
+hi
+
+ +

Java字符串和JavaScript字符串

+ +

请记住,Java字符串和JavaScript字符串是一样的。Java字符串类型的实例,java.lang.String ,并具有由该类定义的所有方法。JavaScript字符串具有由...定义的方法,String.prototype. 最常见的绊脚石是 length, 这是Java字符串方法和JavaScript字符串的动态属性:

+ +
js> javaString = new java.lang.String("Java")
+Java
+js> jsString = "JavaScript"
+JavaScript
+js> javaString.length()
+4
+js> jsString.length
+10
+
+ +

Rhino 在减少这两种类型之间的差异方面提供了一些帮助。首先,您可以将JavaScript字符串传递给需要Java字符串的Java方法,Rhino将执行转换。实际上,我们在前面java.lang.String 例子中构造函数调用中看到了这个特性

+ +

如果java.lang.String 类尚未定义它们,Rhino还会使JavaScript方法可用于Java字符串。例如:

+ +
js> javaString.match(/a.*/)
+ava
+
+ +

JavaImporter 构造函数

+ +

JavaImporter是一个新的全局构造函数,它允许在脚本化Java时省略显式的包名称:

+ +
var SwingGui = JavaImporter(Packages.javax.swing,
+                            Packages.javax.swing.event,
+                            Packages.javax.swing.border,
+                            java.awt.event,
+                            java.awt.Point,
+                            java.awt.Rectangle,
+                            java.awt.Dimension);
+...
+
+with (SwingGui) {
+    var mybutton = new JButton(test);
+    var mypoint = new Point(10, 10);
+    var myframe = new JFrame();
+...
+}
+
+ +

以前,这样的功能仅适用于将 org.mozilla.javascript.ImporterTopLevel 用作顶级作用域的嵌入。这个类提供额外的 importPackage() 和importClass() 全局函数的脚本,但其广泛的使用有污染Java类名的全局命名空间的趋势,还有防止垃圾收集加载类。

+ +

详情请参阅 Bugzilla 245882.

+ +

Java 异常

+ + + +

JavaScript代码使用 try ... catch 语句可以捕获Java方法抛出的异常Rhino将Java异常封装到具有以下属性的错误对象中:

+ + + +

instanceof运算符可用于查询异常的类型:

+ + + +
try {
+    java.lang.Class.forName("NonExistingClass");
+} catch (e) {
+    if (e.javaException instanceof java.lang.ClassNotFoundException) {
+       print("Class not found");
+    }
+}
+
+ +

Rhino 还支持对 try... catch 语句的扩展,允许定义条件捕获异常:

+ +
function classForName(name) {
+    try {
+        return java.lang.Class.forName(name);
+    } catch (e if e.javaException instanceof java.lang.ClassNotFoundException) {
+        print("Class " + name + " not found");
+    } catch (e if e.javaException instanceof java.lang.NullPointerException) {
+        print("Class name is null");
+    }
+}
+
+classForName("NonExistingClass");
+classForName(null);
+
diff --git a/files/zh-cn/mozilla/projects/rhino/shell/index.html b/files/zh-cn/mozilla/projects/rhino/shell/index.html new file mode 100644 index 0000000000..d5a4b779a9 --- /dev/null +++ b/files/zh-cn/mozilla/projects/rhino/shell/index.html @@ -0,0 +1,179 @@ +--- +title: Shell +slug: Mozilla/Projects/Rhino/Shell +translation_of: Mozilla/Projects/Rhino/Shell +--- +

JavaScript的外壳提供了一个简单的方法来在批处理模式下或编程的一个探索性的互动环境运行脚本.

+

调用Shell

+

<big>java org.mozilla.javascript.tools.shell.Main {{ mediawiki.external('options') }} script-filename-or-url {{ mediawiki.external('script-arguments') }} </big>

+

这里是一些选项 options

+

-e script-source

+

script-source  作为 JavaScript 执行.

+

-f script-filename-or-url

+

读取script-filename-or-url 的内容并作为JavaScript执行.

+

-opt optLevel / -O optLevel

+

优化等级 optLevel, 必须是 -1 或 [0-9]之间的整数. 参考Rhino Optimization 或许详情.

+

-version versionNumber

+

制定语言编译版本. 字符串 versionNumber 必须是 100, 110, 120, 130, 140, 150, 160170. 参考JavaScript Language Versions获取更多的语言版本信息.

+

-strict

+

开启strict 模式.

+

-continuations

+

启用continuation的实验支持,建立优化级别为-1强制解释模式. 从Rhino 1.7 开始这个选项不再可用.

+

注意

+

如果shell被使用设置为true的系统属性rhino.use_java_policy_security调用,一个安全管理将被安装, shell限制脚本通过基于根据URL访问Java安全选项的权限.如果JVM实现Java2的安全模型才可以用.

+

预定义的属性

+

在shell中呗执行的脚本访问顶层定义的一些属性.

+

arguments

+

当shell被调用时,arguments 对象是一个包含所有通过命令行输入的字符串的数组

+

environment

+

返回当前环境对象.

+

history

+

显示命令行中执行命令的历史.

+

help()

+

获取帮助信息.

+

defineClass(className)

+

定义一个使用Java类命名的扩展,参数 className是个类名的字符串. 使用 ScriptableObject.defineClass() 定义扩展.

+

deserialize(filename)

+

从指定的文件恢复以前通过调用一个被serialize的对象.

+

gc()

+

运行垃圾回收器.

+

load([filename, ...])

+

载入字符串命名的参数JavaScript源码文件. 如果有多个参数被传递,那么每一个参数都会被读取并执行.

+

loadClass(className)

+

载入并执行字符串className.表示的类.这个类必须是已实现的脚本接口, 就像任何被编译的脚本 Rhino JavaScript Compiler.

+

print([expr ...])

+

评估并打印表达式. 评估每一个表达式, 把结果转化为字符串并打印.

+

readFile(path [, characterCoding])

+

读取给定的文件并使用指定的编码把字节转换为字符串,如果没有制定编码就用默认编码.

+

readUrl(url [, characterCoding])

+

打开指定的url,读取所有的字节并用指定的编码转化为数组,如果没有指定编码就是用默认的.

+

runCommand(commandName, [arg, ...] [options])

+

执行参数中给定的命令,作为一个独立的进程选项并返回该进程的退出状态.

+

Usage:

+
runCommand(command)
+runCommand(command, arg1, ..., argN)
+runCommand(command, arg1, ..., argN, options)
+
+

All except the last arguments to runCommand are converted to strings and denote command name and its arguments. If the last argument is a JavaScript object, it is an option object. Otherwise it is converted to string denoting the last argument and options objects assumed to be empty.

+

The following properties of the option object are processed:

+ +

seal(object)

+

Seal the specified object so any attempt to add, delete or modify its properties would throw an exception.

+

serialize(object, filename)

+

Serialize the given object to the specified file.

+

spawn(functionOrScript)

+

Run the given function or script in a different thread.

+

sync(function)

+

creates a synchronized function (in the sense of a Java synchronized method) from an existing function. The new function synchronizes on the this object of its invocation.

+

quit()

+

退出shell. 如果文件字符是在提示符下键入,shell将也退出在交互模式下.

+

version([number])

+

设置或获取JavaScript的版本号. 如果没有参数,就返回当前的版本. 如果有参数,参数要在 100, 110, 120, 130, 140, 150, 160 或 170范围内,它们分别对应 JavaScript1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6 or 1.7.

+

例子

+

调用

+

Here the shell is invoked three times from the command line. (The system command prompt is shown as $.) The first invocation executes a script specified on the command line itself. The next invocation has no arguments, so the shell goes into interactive mode, reading and evaluating each line as it is typed in. Finally, the last invocation executes a script from a file and accesses arguments to the script itself.

+
$ java org.mozilla.javascript.tools.shell.Main -e print('hi')
+hi
+$ java org.mozilla.javascript.tools.shell.Main
+js> print('hi')
+hi
+js> 6*7
+42
+js> function f() {
+  return a;
+}
+js> var a = 34;
+js> f()
+34
+js> quit()
+$ cat echo.js
+for (i in arguments) {
+  print(arguments[i])
+}
+$ java org.mozilla.javascript.tools.shell.Main echo.js foo bar
+foo
+bar
+$
+
+

spawn 和 sync 

+

下面的例子创建了2个线程 via spawn 和 uses sync 去创建同步的函数test test版本.

+
js> function test(x) {
+  print("entry");
+  java.lang.Thread.sleep(x*1000);
+  print("exit");
+}
+js> var o = { f : sync(test) };
+js> spawn(function() {o.f(5);});
+Thread[Thread-0,5,main]
+entry
+js> spawn(function() {o.f(5);});
+Thread[Thread-1,5,main]
+js>
+exit
+entry
+exit
+
+

运行命令

+

这是在Linux下调用 runCommand 的例子.

+
js> runCommand('date')
+Thu Jan 23 16:49:36 CET 2003
+0
+// Using input option to provide process input
+js> runCommand("sort", {input: "c\na\nb"})
+a
+b
+c
+0
+js> // Demo of output and err options
+js> var opt={input: "c\na\nb", output: 'Sort Output:\n'}
+js> runCommand("sort", opt)
+0
+js> print(opt.output)
+Sort Output:
+a
+b
+c
+js> var opt={input: "c\na\nb", output: 'Sort Output:\n', err: ''}
+js> runCommand("sort", "--bad-arg", opt)
+2
+js> print(opt.err)
+/bin/sort: unrecognized option `--bad-arg'
+Try `/bin/sort --help' for more information.
+
+js> runCommand("bad_command", "--bad-arg", opt)
+js: "<stdin>", line 18: uncaught JavaScript exception: java.io.IOException: bad_command: not found
+js> // Passing explicit environment to the system shell
+js> runCommand("sh", "-c", "echo $env1 $env2", { env: {env1: 100, env2: 200}})
+100 200
+0
+js> // Use args option to provide additional command arguments
+js> var arg_array = [1, 2, 3, 4];
+js> runCommand("echo", { args: arg_array})
+1 2 3 4
+0
+
+

Windows下的例子也差不多:

+
js> // Invoke shell command
+js> runCommand("cmd", "/C", "date /T")
+27.08.2005
+0
+js> // Run sort collectiong the output
+js> var opt={input: "c\na\nb", output: 'Sort Output:\n'}
+js> runCommand("sort", opt)
+0
+js> print(opt.output)
+Sort Output:
+a
+b
+c
+js> // Invoke notepad and wait until it exits
+js> runCommand("notepad")
+0
+
+

{{ languages( { "zh-cn": "zh-cn/Shell" } ) }}

diff --git a/files/zh-cn/mozilla/projects/social_api/index.html b/files/zh-cn/mozilla/projects/social_api/index.html new file mode 100644 index 0000000000..55d8b5525e --- /dev/null +++ b/files/zh-cn/mozilla/projects/social_api/index.html @@ -0,0 +1,97 @@ +--- +title: Social API +slug: Mozilla/Projects/Social_API +tags: + - API + - Landing + - Mozilla + - NeedsTranslation + - Social + - TopicStub +translation_of: Archive/Social_API +--- +

The Social API is an architecture that makes it easier for web browsers to integrate with social media services, using standard web technologies as the API. Once a social service provider is implemented for Firefox, it becomes possible for the browser to integrate web resources from a service, in-chrome user controls and information related to that service. The following articles explain how to implement a social service provider.
+
+ The Social API supports specific vertical use cases centered around social interactions, but does not tightly constrain those use cases, allowing flexibility and creativity for 3rd parties. Specific features supported are notifications, share, bookmarking (or save-for-later), sidebars and communications (e.g. chat and video).

+ +
+
+

Social API documentation

+ +
+
Social API glossary
+
Provides definitions of key terms you'll need to understand when using the Social API.
+
Social service manifest
+
A description of—(TBD: and guide to building)—the manifest required.
+
Social service worker API reference {{obsolete_inline(48)}}
+
A reference to the social service worker API.
+
Social service content API: MozSocial {{obsolete_inline(51)}}
+
A reference to the social service content API, which is provided by the {{domxref("navigator.MozSocial")}} object.
+
Social share API
+
A reference to the Share API.
+
Social bookmarks API {{obsolete_inline(51)}}
+
A reference to the Social Bookmarks API.
+
Social status API {{obsolete_inline(51)}}
+
A reference to the Status API.
+
Social service widgets
+
A guide to the widgets provided by the social service.
+
+ +

How to create a SocialAPI Provider

+ +

A step-by-step guide to create a simple Social API provider.

+ +
+
First Steps
+
The basics of getting an installable social provider running.
+
Adding ambient notifications {{obsolete_inline(51)}}
+
A short guide to implementing ambient notifications using the Social API.
+
Implementing status and notifications {{obsolete_inline(51)}}
+
A guide to implementing a status panel with notifications using the Social API.
+
Adding bookmark support {{obsolete_inline(51)}}
+
A short guide to implementing social bookmarks using the Social API.
+
Implementing share
+
A guide to implementing a share panel using the Social API.
+
Supporting chat {{obsolete_inline(51)}}
+
A guide to implementing chat features using the Social API.
+
+ +

View All...

+
+ +
+

Getting help from the community

+ +

Need help on a Social API related problem and can't find the solution in the documentation?

+ +
    +
  • Ask your question on the Mozilla IRC channel: #socialdev
  • +
+ +

Don't forget about the netiquette...

+ +

Tools and demos

+ + + +

View All...

+ + + +

Try out any of several providers on the SocialAPI Directory site (Firefox 29 or later required)

+ + + + + +
+
+ +

 

diff --git a/files/zh-cn/mozilla/projects/social_api/share/index.html b/files/zh-cn/mozilla/projects/social_api/share/index.html new file mode 100644 index 0000000000..844ac9d693 --- /dev/null +++ b/files/zh-cn/mozilla/projects/social_api/share/index.html @@ -0,0 +1,86 @@ +--- +title: Share +slug: Mozilla/Projects/Social_API/Share +translation_of: Archive/Social_API/Share +--- +

这一篇只是初步草案,可能会被改变。分享从 [TBD: Firefox 23] 开始可用。

+ +

A service provider may choose to provide a Share panel that users can use to share content from the current browser tab with their friends.  The Share panel is slightly different from other Social UI in the browser.  The Share panel itself contains a list of providers that support the share functionality.  When a user shares a page, they can choose which provider they want to share with.  Each provider may have differing functionality, such as simply providing a comment box to extensive functionlality allowing for image selection and more.

+ +

Share is initiated by the user either through the share button in the toolbar or a context menu.  The user can select an image or text in a page to be shared, or share the page itself.  Links within a page may also be shared without visiting the link.

+ +

A provider implementing support for share may choose to use a URL template that is compatible with OExchange, however the browser also sends a DOM event to the page after load containing details of the share.  In some circumstances, such as sharing a link on the page, the browser will not have detailed information.  Using the DOM event allows the provider to display information about the page being shared without needing to fetch it themselves and parse the page for information.  The browser includes certain META tags, including OpenGraph tags in the event data.

+ +

A User Experience Flow for Share

+ +

SocialAPI content works different than typical web pages.  The are presented as primary UI in the browser, and may be confined in size, live longer than a browser tab, and more.  How your user will interact with your share panel is unique and you will need to take into account how a user should experience your share panel.

+ +

[TODO: describe the expected flow here]

+ +

OpenGraphData DOM Event

+ +

The share page can listen for the OpenGraphData DOM Event.

+ +
addEventListener("OpenGraphData", function(e) {
+  var shareData = JSON.parse(e.detail);
+  $("#shared").text(shareData.url);
+})
+
+ +

Attributes

+ +

The event detail can contain the following attributes which are retreived from META tags and other tags within HEAD, such as the TITLE tag:

+ + + +

Share URL Template

+ +

While we prefer the use of the DOM event, many sites have existing endpoints that allow users to share to that site.  SocialAPI supports using a URL template to make implementation easy for sites that already have this functionality.  In your manifest, you can define your shareURL in this format:

+ +
"shareURL": "https://yoursite.com/share?u=%{url}&t=%{title}
+ +

The %{name} values will be replaced with the following attributes if available.  Otherwise that parameter is removed from the final url used to load your share endpoint.

+ + + +

How to properly size your share panel

+ +

Your share panel is presented in a door hanger from the browser toolbar.  While it can be flexible in size, there is a minimum and a maximum size that the panel will allow.  You also need to implement a couple items to help the browser identify the size you need for your panel.  There are a few ways you can define the proper size for your panel, here are some examples:

+ +

Styling the BODY element

+ +

By default the browser will look at the body.style.width and body.style.height, also taking into account the margin.  It will try to size the panel to show your full page.

+ +
<html>
+<body style="width: 300px; height: 400px">
+</body>
+</html>
+
+ +

Identifying a content element

+ +

The browser will also look to see if you have defined a primary content element.  If you have, then it will use the width and height styles from that element to size the panel.  You will need to make sure that your content element is properly placed.

+ +
<html>
+<body contentid="content">
+<div id="content" style="width: 300px; height: 400px; top: 0; left: 0;"/>
+</body>
+</html>
diff --git a/files/zh-cn/mozilla/projects/spidermonkey/build_documentation/index.html b/files/zh-cn/mozilla/projects/spidermonkey/build_documentation/index.html new file mode 100644 index 0000000000..ecb793016e --- /dev/null +++ b/files/zh-cn/mozilla/projects/spidermonkey/build_documentation/index.html @@ -0,0 +1,294 @@ +--- +title: SpiderMonkey Build Documentation +slug: Mozilla/Projects/SpiderMonkey/Build_Documentation +translation_of: Mozilla/Projects/SpiderMonkey/Build_Documentation +--- +
{{SpiderMonkeySidebar("General")}}
+ +

构建 SpiderMonkey

+ +

使用本说明来构建最新的 SpiderMonkey 源码.

+ +

在构建前, 确保有适合你计算机的构建工具: Linux, Windows, Mac, others. 当构建的版本低于28, 你还需要外加 NSPR.

+ +

以及理所当然地, 你需要 获取 SpiderMonkey 源代码。

+ +

非开发者 (优化) 模式构建

+ +

如果你想在生产环境中安装使用SpiderMonkey或运行标准性能测试,可以使用此步骤。 (如果你想在你的C++应用中把 SpiderMonkey 作为库使用, 或从事改进 SpiderMonkey 本身的工作, 按之后的描述,使用 开发者/调试 模式构建.)

+ +
cd js/src
+autoconf2.13
+
+# This name should end with "_OPT.OBJ" to make the version control system ignore it.
+mkdir build_OPT.OBJ
+cd build_OPT.OBJ
+../configure
+# Use "mozmake" on Windows
+make
+
+ +

一些注意事项:

+ + + +
+

Note: If you are on Mac and getting an error similar to

+ +

"checking whether the C compiler (gcc-4.2  ) works... no
+ configure: error: installation or configuration problem: C compiler cannot create executables.
"

+ +

You can try configuring like so:

+ +
CC=clang CXX=clang++  ../configure
+ +

It is also possible that baldrdash  may fail to compile with

+ +
/usr/local/Cellar/llvm/7.0.1/lib/clang/7.0.1/include/inttypes.h:30:15: fatal error: 'inttypes.h' file not found
+
+/usr/local/Cellar/llvm/7.0.1/lib/clang/7.0.1/include/inttypes.h:30:15: fatal error: 'inttypes.h' file not found, err: true
+ +

This is because, starting from Mohave, headers are no longer installed in /usr/include. Refer the release notes  under Command Line Tools -> New Features

+ +

The release notes also states that this compatibility package will no longer be provided in the near future, so the build system on macOS will have to be adapted to look for headers in the SDK
+
+ Until then, the following should help,

+ +
open /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pk
+
+
+ +

This builds an executable named js in the directory build-release/dist/bin. You can test it with dist/bin/js --help, which displays a help page. At this point, you're ready to run and try out the shell.

+ +

On Mac, Linux, or UNIX, you can install SpiderMonkey on your system with the additional command make install. This installs the shared library to /usr/local/lib, the C header files to /usr/local/include, and the js executable to/usr/local/bin.

+ +

开发者 (调试) 模式构建

+ +

For developing and debugging SpiderMonkey itself, it is best to have both a debug build (for everyday debugging) and an optimized build (for performance testing), in separate build directories. Thus, in addition to following the steps above, you should also create a debug build using these steps:

+ +
cd js/src
+autoconf2.13
+
+# This name should end with "_DBG.OBJ" to make the version control system ignore it.
+mkdir build_DBG.OBJ
+cd build_DBG.OBJ
+../configure --enable-debug --disable-optimize
+# Use "mozmake" on Windows
+make
+
+ +

You can also build debug builds of SpiderMonkey with the JS_GC_ZEAL option, which adds a new built-in function to SpiderMonkey that lets you configure zealous garbage collection.  This can help debug memory leaks and other memory-related problems. See JS_SetGCZeal() for details.

+ +

For a list of other available build options, type (assuming the current working directory is one of the above-created build directories):

+ +
../configure --help
+
+ +

生成编译数据库

+ +

Some tools (like IDEs, static analyzers and refactoring tools) consume a file called compile_commands.json which contains a description of all the pieces required to build a piece of software so that tools don't have to also understand a build system.

+ +

To generate a compile_commands.json with the SpiderMonkey configure script, enable the CompileDB backend, like this:

+ +
 ../configure <options> --enable-build-backends=CompileDB,RecursiveMake
+
+ +

(RecursiveMake is there as you'd likely also want to be able to build!)

+ +

Windows Builds

+ +
+

Since version 28, threadsafe builds are the default, and should work out of the box on all POSIX platforms. Hence, the following instructions should only be relevant if you're on Windows or compiling an older version of SpiderMonkey.

+
+ +

The MozillaBuild batch file you used to open your shell (e.g. start-shell-msvc2013.bat or start-shell-msvc2013-x64.bat) determines whether the compiler toolchain will target 32-bit or 64-bit builds. To create a 64-bit build, note that you must configure with --target=x86_64-pc-mingw32 --host=x86_64-pc-mingw32.

+ +

Since the POSIX NSPR emulation is not available for Windows, a working version of NSPR must be available to your build. The easiest option is to configure with --enable-nspr-build. This configure option builds the in-tree version of NSPR which is probably what you want; because SpiderMonkey uses newer NSPR symbols, the NSPR that ships with your operating system probably does not work.

+ +

If --enable-nspr-build does not work, explicitly tell configure where to find NSPR using the --with-nspr-cflags and --with-nspr-libs configure options. For example, assuming your local NSPR has been installed to C:/mozilla-build/msys/local:

+ +
./configure --with-nspr-cflags="-IC:/mozilla-build/msys/local/include" \
+            --with-nspr-libs="C:/mozilla-build/msys/local/lib/libnspr4.a \
+                              C:/mozilla-build/msys/local/lib/libplds4.a \
+                              C:/mozilla-build/msys/local/lib/libplc4.a"
+
+ +

If you get symbol loading or dynamic library errors, you can force the correct NSPR to load with:

+ +
PATH="$PATH;C:/mozilla-build/msys/local/lib/" ./js
+ +

指定安装目录

+ +

make install puts files in the following directories by default. You can override this by passing options to the configure script:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
What it isWhere it gets putconfigure option
executables, shell scripts/usr/local/bin--bindir
libraries, data/usr/local/lib--libdir
architecture-independent data/usr/local/share--sharedir
C header files/usr/local/include--includedir
+ +

For convenience, you can pass the configure script an option of the form --prefix=<PREFIXDIR>, which substitutes <PREFIXDIR> for /usr/local in all the settings above, in one step. This is usually the least troublesome thing to do, as it preserves the typical arrangement of lib, bin, and the rest.

+ +
Note: All directories you pass to configure are recorded in the generated makefile, so you don't need to specify them again until you re-run configure.
+ +

构建 SpiderMonkey 作为静态库

+ +

默认情况下, SpiderMonkey 会构建为共享库. However, you can build SpiderMonkey as a static library by specifying the --disable-shared-js flag when you run configure.

+ +

指定编译器及编译标签

+ +

If you want to use a compiler other than the one the configure script chooses for you by default, you can set the CXX variable in the environment when you run configure. This will save the values you specify in the generated makefile, so once you've set it, you don't need to do so again until you re-run configure.

+ +

If you'd like to pass certain flags to the compiler, you can set the CXXFLAGS environment variable when you run configure. For example, if you're using the GNU toolchain, the following will pass the -g3 flag to the compiler, causing it to emit debug information about macros. Then you can use those macros in gdb commands:

+ +
$ CXXFLAGS=-g3 $SRC/configure
+...
+checking whether the C++ compiler (c++ -g3 ) works... yes
+...
+$
+
+ +

交叉编译选项

+ +

For cross-compiling you will need a cross-compiling compiler. That tends to be easier with clang as clang has cross-compiling support built in. You may need other libraries though.  For example on debian linux you'll need the following to cross compile from x86_64 to x86.

+ +
apt install clang libstdc++-8-dev-i386-cross binutils-i686-gnu zlib1g-dev:i386
+ +

You'll also need rust, in addition to having normal rust set up you'll need to add another target to your existing rust toolchain (don't add a new toolchain spidermonkey will use only one toolchain and use it for both host and target code:

+ +
rustup target add i686-unknown-linux-gnu
+ +

To build a 32-bit version on a 64-bit Linux system, you can use the following:

+ +
PKG_CONFIG_LIBDIR=/usr/lib/pkgconfig CC="gcc -m32 -mfpmath=sse -msse -msse2" CXX="g++ -m32 -mfpmath=sse -msse -msse2" AR=ar \
+$SRC/configure --target=i686-pc-linux
+
+ +

Or for clang.

+ +
$SRC/configure --target=i686-pc-linux-gnu
+ +

To build a 32-bit arm version on a 64-bit Linux system, that runs in the arm simulator, you can use the following:

+ +
   AR=ar CC="gcc -m32 -mfpmath=sse -msse -msse2" CXX="g++ -m32 -mfpmath=sse -msse -msse2" \
+    $SRC/configure --target=i686-pc-linux --enable-simulator=arm
+
+ +

To build a 32-bit version on a 64-bit Mac system (the target version is specific to your OS/X SDK), you can use the following:

+ +
$SRC/configure --target=i386-apple-darwin16.7.0 # Choose the appropriate SDK version for your version of OS/X
+ +

To build a 64-bit version on a 32-bit Mac system (e.g. Mac OS X 10.5), you can use the following:

+ +
AR=ar CC="gcc -m64" CXX="g++ -m64" ../configure --target=x86_64-apple-darwin10.0.0
+
+ +

To build a 64-bit Windows version, you can use the following:

+ +
$SRC/configure --host=x86_64-pc-mingw32 --target=x86_64-pc-mingw32
+
+ +
Note: You must have started your MozillaBuild shell with the proper -x64.bat script in order for the 64-bit compilers to be in your PATH.
+ +

Whatever compiler and flags you pass to configure are recorded in the generated makefile, so you don't need to specify them again until you re-run configure.

+ +

Building your application

+ +

While "How to build your complete application" is clearly out of scope for this document, here are some tips that will help get you on your way:

+ + + +

Using the js-config script

+ +

In addition to the SpiderMonkey libraries, header files, and shell, the SpiderMonkey build also produces a shell script named js-config which other build systems can use to find out how to compile code using the SpiderMonkey APIs, and how to link with the SpiderMonkey libraries.

+ +
Note: In SpiderMonkey 1.8.5, the js-config script is not generated properly on many platforms. If the instructions below do not work, you can try this workaround.
+ +

When invoked with the --cflags option, js-config prints the flags that you should pass to the C compiler when compiling files that use the SpiderMonkey API. These flags ensure the compiler will find the SpiderMonkey header files.

+ +
$ ./js-config --cflags # Example output: -I/usr/local/include/js -I/usr/include/nspr
+
+ +

When invoked with the --libs option, js-config prints the flags that you should pass to the C compiler when linking an executable or shared library that uses SpiderMonkey. These flags ensure the compiler will find the SpiderMonkey libraries, along with any libraries that SpiderMonkey itself depends upon (like NSPR).

+ +
$ ./js-config --libs # Example output: -L/usr/local/lib -lmozjs -L/usr/lib -lplds4 -lplc4 -lnspr4 -lpthread -ldl -ldl -lm  -lm -ldl
+ +

Testing SpiderMonkey

+ + + +

Building SpiderMonkey 1.8 or earlier

+ +

Use these instructions to build SpiderMonkey from an official source release or from the old CVS repository. To build the latest SpiderMonkey sources from Mercurial, see Building SpiderMonkey above.

+ +

SpiderMonkey is easy to build from source if you have the usual Mozilla build prerequisites installed. Before you begin, make sure you have right build tools for your computer: LinuxWindowsMacothers.

+ +

First, download a SpiderMonkey source distribution, such as SpiderMonkey 1.8 Release Candidate 1.

+ +

To build, use these commands:

+ +
tar xvzf js-1.8.0-rc1.tar.gz
+cd js/src
+make -f Makefile.ref
+
+ +

This builds a debug version of SpiderMonkey. All build files are created in a subdirectory named depending on your system (for example,Linux_All_DBG.OBJ if you are on Linux). To install this build on your system, see SpiderMonkey installation instructions.

+ +

To build an optimized (non-debug) version of SpiderMonkey:

+ +
make BUILD_OPT=1 -f Makefile.ref
+ +

To build a thread-safe version of SpiderMonkey:

+ +
make JS_DIST=/full/path/to/directory/containing/nspr JS_THREADSAFE=1 -f Makefile.ref
+
diff --git a/files/zh-cn/mozilla/projects/spidermonkey/comparision_of_js_engines/index.html b/files/zh-cn/mozilla/projects/spidermonkey/comparision_of_js_engines/index.html new file mode 100644 index 0000000000..934e38ad7a --- /dev/null +++ b/files/zh-cn/mozilla/projects/spidermonkey/comparision_of_js_engines/index.html @@ -0,0 +1,105 @@ +--- +title: JS 引擎比较 +slug: Mozilla/Projects/SpiderMonkey/Comparision_of_JS_engines +--- +

概述

+

本页用来纪录各个开源 JS 引擎(SpiderMonkey、V8、JavaScriptCore)在算法、未来趋势上的比较。除非额外说明,内存相关的数据假设系统为 32 位

+

类、函数、词汇比较表

+

为了让懂得其中一个 JS 引擎的程序员迅速了解另外一个引擎,以下整理这些引擎共同概念的实现比较(把鼠标放在类/函数上面可以找到定义该类/函数的文件):

+

常见

+ + + + + + + + + + + + + + + + + + + + + + + + + +
SpiderMonkeyV8备注
ValueMaybeObject *代表一个 JS 值(数值、字符串、对象……)的类。SpiderMonkey 是用 nun-boxing,总是一个 double 的大小(因此在 32 位的系统下,传值需要两个 cycle)。V8 是用 tagged pointer,总是一个指针的大小,浮点数存在堆上。MaybeObject 还是很多非 JS 语言对象(代码块等等)的父类
 ObjectImplJSObjectJS 对象(obj instanceof Object)的实现类。SpiderMonkey 与 V8 皆是把部分属性存放在对象行内,部分用外链的一个数组储存的模式。SpiderMonkey 也将小数组的数据存在行内(但是不会分两半),而 V8 的 JS 数组对象(貌似)都是将数据存在外链的数组上。在 SpiderMonkey 中,只有在 new space 的 JS 对象的外链数组的空间由虚拟机分配,其他情况的外链数组的空间malloc 分配(因此内存会比较分裂?)。ObjectImpl 除了有连接到 Shape 的指针之外,还有一个链到 TypeObject 的指针:16 B(ObjectImpl)vs. 12 B(JSObject)。在 SpiderMonkey 中,数据用 Value 存,也就是说,对于一个有 k 个行内属性的 JS 对象来说,内存占用是:16 B + k * 8 B(ObjectImpl)vs. 12 B + k * 4 B(JSObject),行外的情形 V8 则会再多用 8 B(FixedArray 的标头)。
ShapeTypeObjectClassMap隐藏类的实现类。在 SpiderMonkey 中,属性名存在 Shape 上(因此带有 V8 的 DescriptorArray 的作用),JS 对象的原型存在 TypeObject 上,特殊属性的处理方法存在 Class 上(Class 对象不是 JS 堆里的对象,大部分都共用:JSObject::class_JSFunction::class_……)。由于 V8 的 Map 有 SM 三个类的作用,因此占用内存也比较多:24 B(Shape)vs. 40 B(Map)。
+

内存布局与对象创建

+

运行时

+ + + + + + + + + + + + + +
SpiderMonkeyV8备注
Interpret(无)解释器的主回圈。V8 没有字节码与解释器。
+

堆与 GC

+ + + + + + + + + + + + + +
SpiderMonkeyV8备注
NurseryNewSpace 
+

调优

+

一个容易调优的 JS 引擎应该具备有以下条件(从重要的到不重要的):

+ +

参见

+ +

跟 “JS 引擎” 比较无关,但是中文的 JS 引擎相关的博文也比较少,这里搜集一下:

+ +

代码美观

+

这件事实在不应该是决定使用哪个 JS 引擎的因素,不过……

+

如果(不幸的)需要以 SpiderMonkey 作为基础调优则会碰到以下问题:

+
    +
  1. C 与 C++ 代码混用。SpiderMonkey 原先是 C 写成的,后来大规模的以 C++ 改进,但是留下了很多残骸:宏、不是宏但是名称是大写的函数。(参见 JS::Value 的说明。)
  2. +
  3. 成员变量、方法命名缺乏规则。ObjectImpl::slotsObjectImpl::shape_ 同时存在(前面那个应该加底线)。这个或许是可以修复的 bug。
  4. +
  5. 混入 JavaScriptCore、V8 代码。SpiderMonkey 的组译器是 JavaScriptCore 的,那些类的成员变量是 m_buffer 等等,又增加了成员变量命名的。另外还有 WTF_* 宏,真是 WTF。再批。妈的,WTF_CPU_ARM_THUMB2 跟本不可能为真,这里有大量的死代码(所有代码完全没有用到 JSC::MacroAssembler,用到的是 js::jit::MacroAssembler)。另外,
  6. +
  7. 混乱的名称空间。
  8. +
  9. structclass 混用。
  10. +
  11. 文档命名缺少规则。C 时代的档名是 jsobj.h,C++ 时代的档名是 Value.h 。请自重。
  12. +
  13. 过渡滥用宏。
  14. +
diff --git a/files/zh-cn/mozilla/projects/spidermonkey/index.html b/files/zh-cn/mozilla/projects/spidermonkey/index.html new file mode 100644 index 0000000000..468fafa0cb --- /dev/null +++ b/files/zh-cn/mozilla/projects/spidermonkey/index.html @@ -0,0 +1,132 @@ +--- +title: SpiderMonkey +slug: Mozilla/Projects/SpiderMonkey +tags: + - SpiderMonkey + - Update +translation_of: Mozilla/Projects/SpiderMonkey +--- +

SpiderMonkey 是Mozilla使用C/C++编写的JavaScript 引擎。它被用于包括Firefox在内的多个Mozilla产品中,使用的是MPL 2授权协议.

+ +

独立的源代码版本可以在发布页上找到

+ + + + + + + + +
+

文档

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+

General

+
SpiderMonkey Build Documentation如何获取到SpiderMonkey源代码,编译,并运行测试套.
Introduction to the JavaScript shell如何获取,构建,并使用JavaScript shell.
Running Automated JavaScript Tests如何运行JavaScript测试套件.
Creating JavaScript tests如何为JavaScript测试套件添加测试.
New to SpiderMonkeySpiderMonkey的hacking指南.
Setting up CDT to work on SpiderMonkey如何配置CDT,使之在SpiderMonkey代码上工作.
+

JSAPI

+
JSAPI User Guide本指南简要介绍了SpiderMonkey,还介绍了如何可以将SpiderMonkey嵌入到你的应用程序中.
JSAPI Phrasebook一些常用的JavaScript表达式和语句的JSAPI翻译.
JSAPI ReferenceSpiderMonkey API 参考.
Bytecode ReferenceSpiderMonkey 字节码参考.
JS Debugger API Guide在Gecko 8.0中引入的新的JavaScript调试器API{{ geckoRelease("8.0") }}.
JS Debugger API ReferenceSpiderMonkey 1.8.6(Gecko 8.0 )中引入的Debugger对象的API参考, {{ geckoRelease("8.0") }}.
JSDBGAPI Reference +

SpiderMonkey调试API参考;SpiderMonkey 1.8.5之前版本的调试API, 虽然它并没有被删除.

+
+

提示,技巧和理念

+
How to embed the JavaScript engine如何嵌入SpiderMonkey的基础教程
SpiderMonkey Garbage Collection Tips如何避免垃圾回收时出现的问题.
SpiderMonkey Internals设计概况和实现版本介绍
SpiderMonkey Internals: GC关于垃圾回收的独立的内部文章.
SpiderMonkey Internals: Thread SafetySpiderMonkey的请求模型的内部工作原理.
+
+ + + + + +

社区

+ +

有问题? 在IRC上提问!

+ +

查看 Infomonkey.

+ +

有bug? 提交bugCore -> JavaScript Engine

+
diff --git a/files/zh-cn/mozilla/projects/spidermonkey/internals/bytecodes/index.html b/files/zh-cn/mozilla/projects/spidermonkey/internals/bytecodes/index.html new file mode 100644 index 0000000000..7c47ffb7ae --- /dev/null +++ b/files/zh-cn/mozilla/projects/spidermonkey/internals/bytecodes/index.html @@ -0,0 +1,30 @@ +--- +title: 字节码 +slug: Mozilla/Projects/SpiderMonkey/Internals/Bytecodes +tags: + - SpiderMonkey +translation_of: Mozilla/Projects/SpiderMonkey/Internals/Bytecodes +--- +
{{SpiderMonkeySidebar("Internals")}}
+ +

背景知识

+ +

SpiderMonkey字节码是JavaScript引擎使用的标准代码表示形式。JavaScript前端根据源文本构建AST,然后根据JSScript数据结构的一部分从AST生成基于堆栈的字节码。字节码可以引用原子和对象(通常通过数组索引),这些原子和对象也包含在JSScript数据结构中。

+ +

在引擎内,所有字节码都在堆栈帧内执行。堆栈帧与全局(顶级)代码和eval代码相关联。堆栈上的框架为几个不同类别的JavaScript值(标记值格式)留出空间。单个JavaScript值空间称为“插槽”,类别为:

+ + + +

还有一些保留给专用功能的插槽,用于处理thiscallee返回值。.

+ +

总有一个“堆栈顶部”(TOS),它对应于推入表达式堆栈的最新值。所有字节码都根据该位置隐式运行。

+ +

字节码列表

+ +

所有操作码都用 [-popcount, +pushcount] 标注,以表示整个执行的堆栈效果。

+ +

字节码列表已移至 SpiderMonkey Internals: Bytecode Descriptions 页面。

diff --git a/files/zh-cn/mozilla/projects/spidermonkey/internals/functions/index.html b/files/zh-cn/mozilla/projects/spidermonkey/internals/functions/index.html new file mode 100644 index 0000000000..91d96b22eb --- /dev/null +++ b/files/zh-cn/mozilla/projects/spidermonkey/internals/functions/index.html @@ -0,0 +1,73 @@ +--- +title: Functions +slug: Mozilla/Projects/SpiderMonkey/Internals/Functions +translation_of: Mozilla/Projects/SpiderMonkey/Internals/Functions +--- +
{{SpiderMonkeySidebar("Internals")}}
+ +

There are several flavors of JavaScript function. All are JSObjects of the same class, js_FunctionClass.

+ +

这里有些Javscript函数,它们属于JSObjects

+ +

(But note that objects of other classes can be callable and can even have typeof obj == "function".)

+ +

(也存在其他可被Call的对象)

+ +

Script functions

+ +

Functions written in JavaScript and compiled to bytecode. There are four variations that affect how NameExpressions are evaluated. (NameExpressions are basic expressions like String and x that would eat up a huge amount of run time if the engine weren't smart enough to avoid symbol table lookups.)

+ +

General closures are the base case. When the function object is created, its parent is set to the first object on the scope chain. When a name is evaluated that doesn't refer to a local variable, the interpreter consults the scope chain to find the variable. When with or eval are used, we have to do this for correctness.

+ +

This is slow, not only because walking the scope chain is a drag, but also because we'd rather avoid actually creating the scope chain at all, if possible. General closures force the interpreter to verify the whole scope chain. So we optimize this when we can.

+ +

These optimizations depend on being sure that we will never have to walk the scope chain, so with and eval inhibit them all.

+ +

Null closures. If we can prove at compile time that a function does not refer to any locals or arguments of enclosing functions, it is a null closure. Since it will never need to walk the scope chain, its parent is the global object. This is the best case. Barring with and eval, all outermost functions are null closures.

+ +

Null closures with upvars. A nested function is algol-like if it is only ever defined and called, and it isn't accessed in any other way (and it is not a generator-function). Such a function is guaranteed never to be called again after the enclosing function exits. An algol-like function may read the local variables and arguments of its immediate enclosing function from the stack, as if by magic. (JSContext::display caches the enclosing function's stack frame.) If that function is also algol-like, its child can read locals and variables from the next enclosing function, and so on. The compiler detects these cases and makes such functions null closures too.

+ +

Flat closures. Suppose a function reads some variables from enclosing functions but is not algol-like. If the function does not assign to any closed-on vars/args, and it only reads closed-on local variables and arguments that never change value after the function is created, then the function can be implemented as a flat closure. When a flat closure is created, all the closed-on values are copied from the stack into reserved slots of the function object. To evaluate a name, instead of walking the scope chain, we just take the value from the reserved slot. The function object's parent is the global object.

+ +

Flat closures and Null closures have been removed:

+ +

https://bugzilla.mozilla.org/show_bug.cgi?id=730497

+ +

https://bugzilla.mozilla.org/show_bug.cgi?id=739808

+ +

Name lookups

+ +

In order of speed, fastest to slowest.

+ +
    +
  1. +

    ARG and LOCAL instructions. If a name definitely refers to an argument or local variable of the immediately enclosing function, it can be accessed using JSOP_{GET,SET,CALL}{ARG,LOCAL} instructions. Some of these can even be fused with other operations into combo instructions like JSOP_GETARGPROP, JSOP_FORLOCAL, and JSOP_INCLOCAL. Because arguments and locals can't be deleted, this optimization is available to all functions, and eval does not interfere with it. But a with block can:

    + +
    function f(s) {
    +    eval(s);
    +    print(s);  // s can be loaded with GETARG
    +    with (obj) {
    +        print(s);  // no GETARG here; s might refer to obj.s
    +    }
    +}
    +
    +
  2. +
  3. +

    UPVAR instructions. JSOP_{GET,CALL}UPVAR (in algol-like functions only, I think?) TODO

    +
  4. +
  5. +

    DSLOT instructions. JSOP_{GET,CALL}DSLOT (in flat closures only) TODO

    +
  6. +
  7. +

    GVAR instructions. Outside all functions, if a name definitely refers to a global for which we have seen a var, const, or function declaration, then we emit a JS_DEFVAR instruction in the script prelude and access the global using JSOP_{GET,SET,CALL}GVAR. This is fast if the global either doesn't exist before the script runs (the script creates it) or it's a non-configurable data property (which amounts to the same thing). Otherwise the GVAR instructions are as slow as NAME instructions.

    + +

    There are also combo instructions JSOP_{INC,DEC}GVAR and JSOP_GVAR{INC,DEC}.

    +
  8. +
  9. +

    NAME instructions. In the worst case we emit JSOP_{,SET,CALL}NAME. These are totally general. They can still be optimized via the property cache; in the worst case we walk the scope chain.

    + +

    In some cases, the JIT can optimize a JSOP_NAME instruction that refers to a variable in an enclosing scope to pull the value directly out of the Call object's dslots.

    + +

    For the expression delete name we always emit JSOP_DELNAME. It's not worth optimizing.

    +
  10. +
diff --git a/files/zh-cn/mozilla/projects/spidermonkey/internals/index.html b/files/zh-cn/mozilla/projects/spidermonkey/internals/index.html new file mode 100644 index 0000000000..03228c312f --- /dev/null +++ b/files/zh-cn/mozilla/projects/spidermonkey/internals/index.html @@ -0,0 +1,292 @@ +--- +title: SpiderMonkey Internals +slug: Mozilla/Projects/SpiderMonkey/Internals +tags: + - Guide + - JavaScript + - NeedsMarkupWork + - NeedsTranslation + - SpiderMonkey + - TopicStub +translation_of: Mozilla/Projects/SpiderMonkey/Internals +--- +

Design walk-through

+ +

At heart, SpiderMonkey is a fast interpreter that runs an untyped bytecode and operates on values of type jsval—type-tagged double-sized values that represent the full range of JavaScript values. In addition to the interpreter, SpiderMonkey contains a Just-In-Time (JIT) compiler, a garbage collector, code implementing the basic behavior of JavaScript values, a standard library implementing ECMA 262-3 §15 with various extensions, and a few public APIs.

+ +

Interpreter

+ +

Like many portable interpreters, SpiderMonkey's interpreter is mainly a single, tremendously long function that steps through the bytecode one instruction at a time, using a switch statement (or faster alternative, depending on the compiler) to jump to the appropriate chunk of code for the current instruction. A JS-to-JS function call pushes a JavaScript stack frame without growing the C stack. But since JS-to-C-to-JS call stacks are common, the interpreter is reentrant.

+ +

Some SpiderMonkey bytecode operations have many special cases, depending on the type of their arguments. Common cases are inlined in the interpreter loop, breaking any abstractions that stand in the way. So optimizations such as dense arrays and the property cache are, alas, not transparently tucked away in the jsarray.* and jsobj.* files. Both guest-star in jsinterp.cpp (to thunderous applause from Firefox users).

+ +

All state associated with an interpreter instance is passed through formal parameters to the interpreter entry point; most implicit state is collected in a type named JSContext. Therefore, almost all functions in SpiderMonkey, API or not, take a JSContext pointer as their first argument.

+ +

Compiler

+ +

The compiler consumes JavaScript source code and produces a script which contains bytecode, source annotations, and a pool of string, number, and identifier literals. The script also contains objects, including any functions defined in the source code, each of which has its own, nested script.

+ +

The compiler consists of: a random-logic rather than table-driven lexical scanner, a recursive-descent parser that produces an AST, and a tree-walking code generator. Semantic and lexical feedback are used to disambiguate hard cases such as missing semicolons, assignable expressions ("lvalues" in C parlance), and whether / is the division symbol or the start of a regular expression. The compiler attempts no error recovery; it bails out on the first error. The emitter does some constant folding and a few codegen optimizations; about the fanciest thing it does is to attach source notes to the script for the decompiler's benefit.

+ +

The decompiler implements Function.toSource(), which reconstructs a function's source code. It translates postfix bytecode into infix source by consulting a separate byte-sized code, called source notes, to disambiguate bytecodes that result from more than one grammatical production.

+ +

Garbage collector

+ +

The GC is a mark-and-sweep, non-conservative (exact) collector. It is used to hold JS objects and string descriptors (but not property lists or string bytes), and double-precision floating point numbers. It runs automatically only when maxbytes (as passed to JS_NewRuntime) bytes of GC things have been allocated and another thing-allocation request is made. JS API users should call JS_GC or JS_MaybeGC between script executions or from the branch callback, as often as necessary.

+ +

Because the GC is exact, C/C++ applications must ensure that all live objects, strings, and numbers are GC-reachable. Many techniques are available; see SpiderMonkey Garbage Collection Tips.

+ +

JavaScript values

+ +

The type jsval represents a JavaScript value.

+ +

The representation is 64 bits and uses NaN-boxing on all platforms, although the exact NaN-boxing format depends on the platform. NaN-boxing is a technique based on the fact that in IEEE-754 there are 2**47 different bit patterns that all represent NaN. Hence, we can encode any floating-point value as a C++ double (noting that JavaScript NaN must be represented as one canonical NaN format). Other values are encoded as a value and a type tag:

+ + + +

Only JIT code really depends on the layout--everything else in the engine interacts with values through functions like JSVAL_IS_INT. Most parts of the JIT also avoid depending directly on the layout: the files PunboxAssembler.h and NunboxAssembler.h are used to generate native code that depends on the value layout.

+ +

Objects consist of a possibly shared structural description, called the map or scope; and unshared property values in a vector, called the slots. Each property has an id, either a nonnegative integer or an atom (unique string), with the same tagged-pointer encoding as a jsval.

+ +

The atom manager consists of a hash table associating strings uniquely with scanner/parser information such as keyword type, index in script or function literal pool, etc. Atoms play three roles: as literals referred to by unaligned 16-bit immediate bytecode operands, as unique string descriptors for efficient property name hashing, and as members of the root GC set for exact GC.

+ +

Standard library

+ +

The methods for arrays, booleans, dates, functions, numbers, and strings are implemented using the JS API. Most are JSNatives. Most string methods are customized to accept a primitive string as the this argument. (Otherwise, SpiderMonkey converts primitive values to objects before invoking their methods, per ECMA 262-3 §11.2.1.)

+ +

Error handling

+ +

SpiderMonkey has two interdependent error-handling systems: JavaScript exceptions (which are not implemented with, or even compatible with, any kind of native C/C++ exception handling) and error reporting. In general, both functions inside SpiderMonkey and JSAPI callback functions signal errors by calling JS_ReportError or one of its variants, or JS_SetPendingException, and returning JS_FALSE or NULL.

+ +

Public APIs

+ +

The public C/C++ interface, called the JSAPI, is in most places a thin (but source-compatible across versions) layer over the implementation. See the JSAPI User Guide. There is an additional public API for JavaScript debuggers, JSDBGAPI, but {{Source("js/jsd/jsdebug.h")}} might be a better API for debuggers. Another API, JSXDRAPI, provides serialization for JavaScript scripts. (XUL Fastload uses this.)

+ +

Just-In-Time compiler

+ +

{{jsapi_minversion_inline("1.8.5")}} SpiderMonkey contains a just-in-time compiler, code-named JägerMonkey, that converts bytecode to machine code for faster execution. The JIT works by detecting commonly executed functions or functions containing hot loops and then compiling these methods into machine code.

+ +

A second JIT, code-named IonMonkey was enabled in Firefox 18.

+ +

Self-hosting of builtin functions in JS

+ +

Starting with Firefox 17, SpiderMonkey has the ability to implement builtin functions in self-hosted JS code. This code is compiled in a special compilation mode that gives it access to functionality that's not normally exposed to JS code, but that's required for safe and specification-conformant implementation of builtin functions.

+ +

All self-hosted code lives in .js files under builtin/. For details on implementing self-hosted builtins, see self-hosting.

+ +

File walkthrough

+ +

jsapi.cpp, jsapi.h

+ +

The public API to be used by almost all client code.

+ +

jspubtd.h, jsprvtd.h

+ +

These files exist to group struct and scalar typedefs so they can be used everywhere without dragging in struct definitions from N different files. The jspubtd.h file contains public typedefs, and is included automatically when needed. The jsprvtd.h file contains private typedefs and is included by various .h files that need type names, but not type sizes or declarations.

+ +

jsdbgapi.cpp, jsdbgapi.h

+ +

The debugging API. Provided so far:

+ +

Traps, with which breakpoints, single-stepping, step over, step out, and so on can be implemented. The debugger will have to consult jsopcode.def on its own to figure out where to plant trap instructions to implement functions like step out, but a future jsdbgapi.h will provide convenience interfaces to do these things. At most one trap per bytecode can be set. When a script (JSScript) is destroyed, all traps set in its bytecode are cleared.

+ +

Watchpoints, for intercepting set operations on properties and running a debugger-supplied function that receives the old value and a pointer to the new one, which it can use to modify the new value being set.

+ +

Line number to PC and back mapping functions. The line-to-PC direction "rounds" toward the next bytecode generated from a line greater than or equal to the input line, and may return the PC of a for-loop update part, if given the line number of the loop body's closing brace. Any line after the last one in a script or function maps to a PC one byte beyond the last bytecode in the script. An example, from perfect.js:

+ +
function perfect(n) {
+  print("The perfect numbers up to " + n + " are:");
+  // We build sumOfDivisors[i] to hold a string expression for
+  // the sum of the divisors of i, excluding i itself.
+  var sumOfDivisors = new ExprArray(n+1,1);
+  for (var divisor = 2; divisor <= n; divisor++) {
+    for (var j = divisor + divisor; j <= n; j += divisor) {
+      sumOfDivisors[j] += " + " + divisor;
+    }
+    // At this point everything up to 'divisor' has its sumOfDivisors
+    // expression calculated, so we can determine whether it's perfect
+    // already by evaluating.
+    if (eval(sumOfDivisors[divisor]) == divisor) {
+      print("" + divisor + " = " + sumOfDivisors[divisor]);
+    }
+  }
+  delete sumOfDivisors;
+  print("That's all.");
+}
+ +

The line number to PC and back mappings can be tested using the js program with the following script:

+ +
load("perfect.js");
+print(perfect);
+dis(perfect);
+print();
+for (var ln = 0; ln <= 40; ln++) {
+    var pc = line2pc(perfect, ln);
+    var ln2 = pc2line(perfect, pc);
+    print("\tline " + ln + " => pc " + pc + " => line " + ln2);
+}
+
+ +

The result of the for loop over lines 0 to 40 inclusive is:

+ +
line 0 => pc 0 => line 16
+line 1 => pc 0 => line 16
+line 2 => pc 0 => line 16
+line 3 => pc 0 => line 16
+line 4 => pc 0 => line 16
+line 5 => pc 0 => line 16
+line 6 => pc 0 => line 16
+line 7 => pc 0 => line 16
+line 8 => pc 0 => line 16
+line 9 => pc 0 => line 16
+line 10 => pc 0 => line 16
+line 11 => pc 0 => line 16
+line 12 => pc 0 => line 16
+line 13 => pc 0 => line 16
+line 14 => pc 0 => line 16
+line 15 => pc 0 => line 16
+line 16 => pc 0 => line 16
+line 17 => pc 19 => line 20
+line 18 => pc 19 => line 20
+line 19 => pc 19 => line 20
+line 20 => pc 19 => line 20
+line 21 => pc 36 => line 21
+line 22 => pc 53 => line 22
+line 23 => pc 74 => line 23
+line 24 => pc 92 => line 22
+line 25 => pc 106 => line 28
+line 26 => pc 106 => line 28
+line 27 => pc 106 => line 28
+line 28 => pc 106 => line 28
+line 29 => pc 127 => line 29
+line 30 => pc 154 => line 21
+line 31 => pc 154 => line 21
+line 32 => pc 161 => line 32
+line 33 => pc 172 => line 33
+line 34 => pc 172 => line 33
+line 35 => pc 172 => line 33
+line 36 => pc 172 => line 33
+line 37 => pc 172 => line 33
+line 38 => pc 172 => line 33
+line 39 => pc 172 => line 33
+line 40 => pc 172 => line 33
+
+ +

jsconfig.h

+ +

Various configuration macros defined as 0 or 1 depending on how JS_VERSION is defined (as 10 for JavaScript 1.0, 11 for JavaScript 1.1, etc.). Not all macros are tested around related code yet. In particular, JS 1.0 support is missing from SpiderMonkey.

+ +

js.cpp, jsshell.msg

+ +

The "JS shell", a simple interpreter program that uses the JS API and more than a few internal interfaces (some of these internal interfaces could be replaced by jsapi.h calls). The js program built from this source provides a test vehicle for evaluating scripts and calling functions, trying out new debugger primitives, etc.

+ +

A look at the places where jsshell.msg is used in js.cpp shows how error messages can be handled in JSAPI applications. These messages can be localized at compile time by replacing the .msg file; or, with a little modification to the source, at run time.

+ +

More information on the JavaScript shell.

+ +

js.msg

+ +

SpiderMonkey error messages.

+ +

jsarray.*, jsbool.*, jsdate.*, jsfun.*, jsmath.*, jsnum.*, jsstr.*

+ +

These file pairs implement the standard classes and (where they exist) their underlying primitive types. They have similar structure, generally starting with class definitions and continuing with internal constructors, finalizers, and helper functions.

+ +

jsobj.*, jsscope.*

+ +

These two pairs declare and implement the JS object system. All of the following happen here:

+ + + +

The details of a native object's map (scope) are mostly hidden in jsscope.{{mediawiki.external('ch')}}.

+ +

jsatom.cpp, jsatom.h

+ +

The atom manager. Contains well-known string constants, their atoms, the global atom hash table and related state, the js_Atomize() function that turns a counted string of bytes into an atom, and literal pool (JSAtomMap) methods.

+ +

jsarena.cpp, jsarena.h

+ +

Last-In-First-Out allocation macros that amortize malloc costs and allow for en-masse freeing. See the paper mentioned in jsarena.h's major comment.

+ +

jsgc.cpp, jsgc.h

+ +

The garbage collector and tracing routines.

+ +

jsinterp.*, jscntxt.*, jsinvoke.cpp

+ +

The bytecode interpreter, and related functions such as Call and AllocStack, live in jsinterp.cpp. The JSContext constructor and destructor are factored out into jscntxt.cpp for minimal linking when the compiler part of JS is split from the interpreter part into a separate program.

+ +

jsinvoke.cpp is a build hack used on some platforms to build js_Interpret under different compiler options from the rest of jsinterp.cpp.

+ +

jstracer.*, nanojit/*

+ +

The tracing JIT. The interface between the JIT and the rest of SpiderMonkey is conceptually small—the interpreter calls into the trace recorder—but as with everything else, there are tendrils everywhere.

+ +

jsemit.*, jsopcode.tbl, jsopcode.*, jsparse.*, jsscan.*, jsscript.*

+ +

Compiler and decompiler modules. The jsopcode.tbl file is a C preprocessor source that defines almost everything there is to know about JS bytecodes. See its major comment for how to use it. For now, a debugger will use it and its dependents such as jsopcode.h directly, but over time we intend to extend jsdbgapi.h to hide uninteresting details and provide conveniences. The code generator is split across paragraphs of code in jsparse.cpp, and the utility methods called on JSCodeGenerator appear in jsemit.cpp. Source notes generated by jsparse.cpp and jsemit.cpp are used in jsscript.cpp to map line number to program counter and back.

+ +

jstypes.h

+ +

Fundamental representation types and utility macros. This file alone among all .h files in SpiderMonkey must be included first by .cpp files. It is not nested in .h files, as other prerequisite .h files generally are, since it is also a direct dependency of most .cpp files and would be over-included if nested in addition to being directly included.

+ +

jsbit.h, jslog2.cpp

+ +

Bit-twiddling routines. Most of the work here is selectively enabling compiler-specific intrinsics such as GCC's __builtin_ctz, which is useful in calculating base-2 logarithms of integers.

+ +

jsutil.cpp, jsutil.h

+ +

The JS_ASSERT macro is used throughout the source as a proof device to make invariants and preconditions clear to the reader, and to hold the line during maintenance and evolution against regressions or violations of assumptions that it would be too expensive to test unconditionally at run-time. Certain assertions are followed by run-time tests that cope with assertion failure, but only where I'm too smart or paranoid to believe the assertion will never fail...

+ +

jsclist.h

+ +

Doubly-linked circular list struct and macros.

+ +

jscpucfg.cpp

+ +

This standalone program generates jscpucfg.h, a header file containing bytes per word and other constants that depend on CPU architecture and C compiler type model. It tries to discover most of these constants by running its own experiments on the build host, so if you are cross-compiling, beware.

+ +

jsdtoa.cpp, jsdtoa.h, dtoa.c

+ +

dtoa.c contains David Gay's portable double-precision floating point to string conversion code, with Permission To Use notice included. jsdtoa.cpp #includes this file.

+ +

jshash.cpp, jshash.h, jsdhash.cpp, jsdhash.h

+ +

Portable, extensible hash tables. These use multiplicative hash for strength reduction over division hash, yet with very good key distribution over power of two table sizes. jshash resolves collisions via chaining, so each entry burns a malloc and can fragment the heap. jsdhash uses open addressing.

+ +

jslong.cpp, jslong.h

+ +

64-bit integer emulation, and compatible macros that use intrinsic C types, like long long, on platforms where they exist (most everywhere, these days).

+ +

jsprf.*

+ +

Portable, buffer-overrun-resistant sprintf and friends. For no good reason save lack of time, the %e, %f, and %g formats cause your system's native sprintf, rather than JS_dtoa(), to be used. This bug doesn't affect SpiderMonkey, because it uses its own JS_dtoa() call in jsnum.cpp to convert from double to string, but it's a bug that we'll fix later, and one you should be aware of if you intend to use a JS_*printf() function with your own floating type arguments - various vendor sprintf's mishandle NaN, +/-Inf, and some even print normal floating values inaccurately.

+ +

prmjtime.c, prmjtime.h

+ +

Time functions. These interfaces are named in a way that makes local vs. universal time confusion likely. Caveat emptor, and we're working on it. To make matters worse, Java (and therefore JavaScript) uses "local" time numbers (offsets from the epoch) in its Date class.

+ +

jsfile.cpp, jsfile.h, jsfile.msg

+ +

Obsolete. Do not use these files.

+ +

Makefile.in, build.mk

+ +

Mozilla makefiles. If you're building Gecko or Firefox, the larger build system will use these files. They are also used for current standalone builds.

+ +

Makefile.ref, rules.mk, config.mk, config/*

+ +

Obsolete SpiderMonkey standalone makefiles from 1.8 and earlier. See SpiderMonkey Build Documentation.

+ +

See also

+ + diff --git a/files/zh-cn/mozilla/projects/spidermonkey/introduction_to_the_javascript_shell/index.html b/files/zh-cn/mozilla/projects/spidermonkey/introduction_to_the_javascript_shell/index.html new file mode 100644 index 0000000000..b570b78d56 --- /dev/null +++ b/files/zh-cn/mozilla/projects/spidermonkey/introduction_to_the_javascript_shell/index.html @@ -0,0 +1,382 @@ +--- +title: JavaScript shell 介绍 +slug: Mozilla/Projects/SpiderMonkey/Introduction_to_the_JavaScript_shell +tags: + - SpiderMonkey + - 蜘蛛猴 +translation_of: Mozilla/Projects/SpiderMonkey/Introduction_to_the_JavaScript_shell +--- +
{{SpiderMonkeySidebar("General")}}
+ +
+

JavaScript shell 是一个命令行程序,它被包含在SpiderMonkey源代码中。它在 JavaScript 中类似于 Python 命令行、Lisp 读取执行循环和 Ruby 中的 irb 。这篇文章解释如何使用 shell 去测试 JavaScript 代码和执行 JavaScript 程序。

+
+ +

要获取 SpiderMonkey JavaScript shell, 请参见 SpiderMonkey 构建文档 或根据你的平台从 Nightly Builds 下载二进制文件。

+ +

对于其他的 JavaScript shells, 参考 JavaScript shells.

+ +
+

注意: 从 SpiderMonkey 44 开始,默认情况下使用标准的、与 Web 兼容的 JavaScript 版本(不再使用JS1.7 +)。 内置的 version() 内置函数仍然可以用来测试遗留功能。

+
+ +

执行JavaScript shell

+ +

jsshell 提供两种操作模式。你既可以交互式操作 shell, 在此模式你可以输入JavaScript 代码并执行。便于实验和测试新特性。你也可以在命令行参数指定一个 JavaScript 代码文件,此文件会自动运行。

+ +

在安装 jsshell 之后,你可以执行以下命令打开交互式终端:

+ +
js
+
+ +
+

注意:如果你在预编译程序执行中遇到
+ "symbol lookup error: ./js: undefined symbol: PR_SetCurrentThreadName"
+ 这样的错误, 请尝试用 run-mozilla.sh 文件执行它:
+ run-mozilla.sh ./js  
+ ——我测试过有效

+
+ +

如果运行 foo.js file中的JavaScript代码,你可以使用以下命令:

+ +
js foo.js
+
+ +

如果想运行 foo.js 然后进入交互模式:

+ +
js -f foo.js -i
+
+ +

说明

+ +
注意: 因为JavaScript shell 用来给 JavaScript 引擎做测试环境, 可用的选项和内置函数可能改变。
+ +

命令行选项

+ +

有许多命令行选项可以控制shell,以下为总结。使用-h选项显示帮助

+ +
+
-c, --compileonly
+
仅编译不执行代码,这是一种方便的检查语法错误的方式。
+
-e script
+
运行指定脚本,script 是将要执行的代码字符串。
+
-f filename
+
执行指定的代码文件。
+
-i
+
启用交互模式。(如果参数中没有文件名这个选项默认打开)
+
--no-ion
+
禁用优化的 JIT 编译器。
+
--no-baseline
+
禁用基准的 JIT 编译器。
+
-P
+
如果文件的第一行是 "/usr/bin/env js -P",文件内容将通过 JavaScript 引擎解释执行。
+
这将允许你在 unix 和 OS X 系统上执行 JavaScript 文件。
+
-s
+
启用严格警告模式.
+
-w, --warnings
+
显示警告消息.
+
-W, --nowarnings
+
隐藏警告消息.
+
+ +

环境选项

+ +

如果设置了这些环境变量,它们将会影响 js shell 的行为。

+ +
+
JS_STDOUT=file
+
将标准输出重定向到文件file
+
JS_STDERR=file
+
将标准输入重定向到文件file
+
+ +

内置函数

+ +

为了使 JavaScript shell 更加实用, 我们提供了一些内置的函数供 JavaScript 程序(包括交互模式下)使用。

+ +
+

注意:这个列表是不完整的而且与 Shell 全局对象 重复。请参见{{Source("js/src/shell/js.cpp")}} (在 shell_functions 附近) 以获取详细信息。

+
+ +

build()

+ +

返回 JavaScript shell 构建的日期和时间.

+ +
Note: clear() 函数如果不带任何参数,将清除包括所有内置方法在内的所有东西。
+ +

clone(function, [scope])

+ +

克隆指定函数对象。如果未指定具体域,新对象的父本和原始对象的相同。否则,新对象被放置于指定域。

+ +

countHeap([start[, kind]])

+ +

{{ jsapi_minversion_inline("1.8") }}   计算堆中活动的回收垃圾数量,或计算给定且不为 null 的可从 start 到达的对象的数量。kind 是“all”(默认)以计算所有事物,或者是“ object”,“ double”,“ string”,“ function”,“ qname”,“ namespace”,“ xml”之一以仅计算此类事物

+ +

dumpHeap([fileName[, start[, toFind[, maxDepth[, toIgnore]]]]])

+ +

{{ jsapi_minversion_inline("1.8") }} 转储所有现存对象的数据 (或有关联的子数据) 到文件。详情参见本函数的C/C++版本: JS_DumpHeap.

+ +

evalcx(string[, object])

+ +

执行 string 中的 JavaScript 代码。如果设置了参数 object,代码将在这个对象中执行,将其视为一个沙盒。

+ +

string 为空且没有设置 object 时,evalcx() 将会返回一个具有“eager” 标准类的新对象

+ +

string 为 "lazy" 且没有设置 object 时,evalcx() 将会返回一个具有“lazy” 标准类的新对象

+ +
注意: evalcx() 仅对进行 JavaScript 引擎极低层工作的开发者有用,用于在 shell 中测试类evalInSandbox 环境
+ +

gc()

+ +

运行垃圾收集器释放内存。

+ +

gcparam(name[, value])

+ +

{{ jsapi_minversion_inline("1.8") }} 读取或配置垃圾收集器参数。

+ +

名称必须是参数key之一 (例如 'maxBytes', 'maxMallocBytes''gcNumber').

+ +

如果value未指定,gcparam()返回与GC参数名name相关联的当前值

+ +

如果value被指定,其必须可转换为uint32,gcparam()将GC参数名设置为value。

+ +

For more information, see the C/C++ functions  JS_SetGCParameter and JS_SetGCParameter.

+ +

gczeal(level)

+ +

{{ jsapi_minversion_inline("1.8") }} DEBUG only. 设置GC zeal级别, 这是一个调试特性。0 是正常的周期性垃圾收集,1是频繁的GC, 2是及其频繁的GC. 除了0以外的都将使JavaScript运行极其缓慢但是可能有助于发现GC相关的 bug. For more information, see the C/C++ version of this function, JS_SetGCZeal.

+ +

getpda(object)

+ +

返回指定对象的属性描述

+ +

getslx(object)

+ +

返回脚本行范围,这是包含指定对象的代码行数

+ +

help([command ...])

+ +

显示有关指定命令或所有可用功能的简要帮助信息(如果未指定命令将显示所有帮助信息)。

+ +

intern(string)

+ +

将指定的字符串 内化到atom表中。每个字符串都有一个唯一的标识符,称为atom。这个系统使得对字符串进行比较变得更加容易。

+ +
Note: This function is intended only for use when testing the JavaScript engine.
+ +

line2pc([function, ] line)

+ +

返回对应于指定行的代码行的程序计数器值。如果指定了函数,那么行就是指定函数的偏移量.

+ +

load(filename1 [filename])

+ +

加载带有指定名称的JavaScript文件.

+ +
Note: For loading non-JavaScript files, use read().
+ +

options([option ...])

+ +

让你设置或获取选项。如果您在命令行上指定选项,那么调用options的结果将指示您所请求的选项。您还可以传递新的选项来设置.

+ +

The available options are:

+ + + + + + + + + + + + + + + + + + + + +
Option NameDescription
strict严格模式 is enabled.
werrorWarnings should be treated as errors.
atlineWhen atline is enabled, 表单的注释 //@line num set the number of the following line to num.
+ +

pc2line(function, [pc])

+ +

返回对应于指定函数的第一行的JavaScript代码的行号. If you specify a program counter offset into the function, the line number of the line of code containing that offset is returned.

+ +

print([expression ...])

+ +

Evaluates the expression(s) and displays the result(s) on stdout, 分隔 by spaces (" ") and 终止 by a newline ("\n").

+ +

putstr(expression)

+ +

Evaluates the expression and displays the result on stdout.

+ +

quit([status])

+ +

Exits the shell. 如果省略,状态默认为0。

+ +

read(filename[, type])

+ +

Reads and returns the contents of file. If type is "binary" returns an Uint8Array, otherwise returns an UTF-8 decoded string.

+ +

readline()

+ +

Reads a single line of input from stdin, returning it to the caller. You can use this to create interactive shell programs in JavaScript.

+ +

Reflect.parse()

+ +

See Parser API.

+ +
Note: This function is intended only for use when testing the JavaScript engine.
+ +

seal(object[, deep])

+ +

密封指定的对象, or an object graph if deep is true. 通过封住对象或对象图,可以禁用这些对象的修改.

+ +

sleep(dt)

+ +

{{ jsapi_minversion_inline("1.8") }} Only in JS_THREADSAFE builds. Sleep for dt seconds. Fractions of a second are supported. Returns true on success, false if the sleep was interrupted.

+ +

stackQuota([number]) {{obsolete_inline}}

+ +

{{ jsapi_minversion_inline("1.8") }} 获取或设置脚本堆栈配额.

+ +

throwError()

+ +

Throws an error from the JS_ReportError() function.

+ +
Note: This function is intended only for use when testing the JavaScript engine.
+ +

trap([function, [pc,]] expression)

+ +

在JavaScript代码的特定点设置trap. 当由pc在函数函数中指定的偏移量即将被执行时,表达式将被求值。

+ +

这是一种强大的调试机制,与line2pc()一起使用. 例如, 如果你想在函数的第6行中显示一条消息, doSomething() 被执行, you can enter the following:

+ +
trap(doSomething, line2pc(doSomething, 6), "print('line 6!\n')");
+
+ +
Note: 当设置陷阱时,程序中的相应字节码将被trap字节码替换,直到您使用untrap() 来移除陷阱。
+ +

untrap(function [, pc])

+ +

Removes a trap from the specified function at the offset pc. If pc isn't specified, the trap is removed from the function's entry point.

+ +

This function has no effect if there is no trap at the specified location.

+ +

version([number])

+ +

The version() function lets you get or set the JavaScript version number. This may be useful for gaining access to syntax only available in certain versions of JavaScript (for example, see Using JavaScript 1.7).

+ +

调试方法

+ +

These built-in functions are only available in DEBUG builds.

+ +

dis([function])

+ +

为整个程序或指定的函数分解JavaScript字节码

+ +

For example, if you enter the JavaScript function below:

+ +
function test() {
+  var i = 3;
+  print(i+2);
+}
+
+ +

Then run the command dis(test);, you get this output:

+ +
main:
+00000:  uint16 3
+00003:  setvar 0
+00006:  pop
+00007:  name "print"
+00010:  pushobj
+00011:  getvar 0
+00014:  uint16 2
+00017:  add
+00018:  call 1
+00021:  pop
+00022:  stop
+
+Source notes:
+  0:     0 [   0] newline
+  1:     3 [   3] decl     offset 0
+  2:     7 [   4] newline
+  3:    18 [  11] xdelta
+  4:    18 [   0] pcbase   offset 11
+
+ +

dissrc([function])

+ +

Disassembles the JavaScript bytecode for the entire program, or for the specified function, showing the source lines. This function only works with programs loaded from files, either using the -f flag on launching the shell, or by using the load() function.

+ +

If your program includes a function, doStuff(), like this:

+ +
function doStuff(input) {
+	print("Enter a number: ");
+	var n1 = readline();
+	print("Enter another one: ");
+	var n2 = readline();
+
+	print("You entered " + n1 + " and " + n2 + "\n");
+}
+
+ +

Calling dissrc(doStuff) function would give this output:

+ +
;-------------------------  10:         print("Enter a number: ");
+00000:  10  name "print"
+00003:  10  pushobj
+00004:  10  string "Enter a number: "
+00007:  10  call 1
+00010:  10  pop
+;-------------------------  11:         var n1 = readline();
+00011:  11  name "readline"
+00014:  11  pushobj
+00015:  11  call 0
+00018:  11  setvar 0
+00021:  11  pop
+;-------------------------  12:         print("Enter another one: ");
+00022:  12  name "print"
+00025:  12  pushobj
+00026:  12  string "Enter another one: "
+00029:  12  call 1
+00032:  12  pop
+;-------------------------  13:         var n2 = readline();
+00033:  13  name "readline"
+00036:  13  pushobj
+00037:  13  call 0
+00040:  13  setvar 1
+00043:  13  pop
+;-------------------------  14:
+;-------------------------  15:         print("You entered " + n1 + " and " + n2 + "\n");
+00044:  15  name "print"
+00047:  15  pushobj
+00048:  15  string "You entered "
+00051:  15  getvar 0
+00054:  15  add
+00055:  15  string " and "
+00058:  15  add
+00059:  15  getvar 1
+00062:  15  add
+00063:  15  string "\\n"
+00066:  15  add
+00067:  15  call 1
+00070:  15  pop
+00071:  15  stop
+
+ +

dumpheap(([fileName[, start[, toFind[, maxDepth[, toIgnore]]]]])

+ +

Dump GC information. This is a thin wrapper for JS_DumpHeap.

+ +

gczeal(zeal)

+ +

Enable extra-frequent GC, to help find GC hazards. zeal is an integer. The meaning is the same as for the parameter to JS_SetGCZeal.

+ +

notes([function])

+ +

Shows the source notes for the specified function. Source notes contain information that map the bytecode to the source code, which is used when decompiling the code, such as when using the dissrc() function.

diff --git "a/files/zh-cn/mozilla/projects/spidermonkey/javascript-c\345\274\225\346\223\216\345\265\214\345\205\245\345\274\200\345\217\221\346\214\207\345\215\227/index.html" "b/files/zh-cn/mozilla/projects/spidermonkey/javascript-c\345\274\225\346\223\216\345\265\214\345\205\245\345\274\200\345\217\221\346\214\207\345\215\227/index.html" new file mode 100644 index 0000000000..4752df82f3 --- /dev/null +++ "b/files/zh-cn/mozilla/projects/spidermonkey/javascript-c\345\274\225\346\223\216\345\265\214\345\205\245\345\274\200\345\217\221\346\214\207\345\215\227/index.html" @@ -0,0 +1,11 @@ +--- +title: JavaScript-C引擎嵌入开发指南 +slug: Mozilla/Projects/SpiderMonkey/JavaScript-C引擎嵌入开发指南 +translation_of: Mozilla/Projects/SpiderMonkey/JSAPI_User_Guide +--- +

查看Nirvana Studio上的翻译 +


+

+
+
+{{ languages( { "en": "en/JSAPI_User_Guide", "ja": "ja/Embedding_SpiderMonkey" } ) }} diff --git a/files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/boolean_to_jsval/index.html b/files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/boolean_to_jsval/index.html new file mode 100644 index 0000000000..80747881fd --- /dev/null +++ b/files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/boolean_to_jsval/index.html @@ -0,0 +1,53 @@ +--- +title: BOOLEAN_TO_JSVAL +slug: Mozilla/Projects/SpiderMonkey/JSAPI_reference/BOOLEAN_TO_JSVAL +translation_of: Mozilla/Projects/SpiderMonkey/JSAPI_reference/BOOLEAN_TO_JSVAL +--- +
{{SpiderMonkeySidebar("JSAPI")}}
+ +
{{ obsolete_header("jsapi42") }}
+ +
+

Cast a C integer to a boolean {{jsapixref("JS::Value")}} without any type checking or error handling.

+
+ +
+

Please use {{jsapixref("JS::BooleanValue")}}/{{jsapixref("JS::TrueValue")}}/{{jsapixref("JS::FalseValue")}} instead in SpiderMonkey 45 or later.

+
+ +

Syntax

+ +
jsval
+BOOLEAN_TO_JSVAL(bool b);
+
+ + + + + + + + + + + + + + +
NameTypeDescription
bboolC integer value to be converted to a boolean jsval.
+ +

Description

+ +

BOOLEAN_TO_JSVAL converts a bool argument, b, to a boolean jsval.

+ +

If b is false, the result is JSVAL_FALSE.

+ +

If b is true, the result is JSVAL_TRUE.

+ +

See Also

+ + diff --git a/files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/index.html b/files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/index.html new file mode 100644 index 0000000000..d076928fba --- /dev/null +++ b/files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/index.html @@ -0,0 +1,646 @@ +--- +title: JSAPI 参考 +slug: Mozilla/Projects/SpiderMonkey/JSAPI_reference +translation_of: Mozilla/Projects/SpiderMonkey/JSAPI_reference +--- +

JSAPI SpiderMonkey JavaScript 引擎的C 语言应用程序接口(API)。要了解如何使用JSAPI ,请看 JSAPI User Guide and the JSAPI Phrasebook

+


+ Alphabetical List

+

运行时和上下文

+ + + + + +

Locale callbacks:

+ +

Locale callback types:

+ +

脚本

+

Just running some JavaScript code is straightforward:

+

只是运行一些JavaScript代码很简单:

+ +

You can instead compile JavaScript code into a JSScript which you can then execute multiple times.

+

你可以将JavaScript代码编译后保存在JSScript类型的变量中,这样就可以多次执行。

+

typedef JSScript

+ +

You can also compile JavaScript code into a function:

+ +

 

+

错误处理

+ +

The following functions allow C/C++ functions to throw and catch JavaScript exceptions:

+ + +

These functions translate errors into exceptions and vice versa:

+ +

值和类型

+ +

jsval constants:

+ +

Function and macros for checking the type of a jsval:

+ +

High-level type-conversion routines for packing and unpacking function arguments.

+ + +

The following functions convert JS values to various types. They can be safely applied to jsvals of any type. They may return new objects. For example, JS_ValueToObject(cx, s) where s is a string creates a new String wrapper object. These functions may call JavaScript methods. For example, JS_ValueToString(cx, obj) may call obj.toString().

+ +

Fast, unchecked type-casting macros. These macros must not be applied to values that are not known to be the right type. Like C casts, they may cause crashes if applied to incorrect values. They never create new objects or call into JavaScript code.

+ +

And:

+ +

Memory management

+

These functions act like the Standard C malloc family of functions, except that errors are reported using the SpiderMonkey error APIs rather than errno. These functions also allow SpiderMonkey to account the number of bytes allocated:

+ +

JavaScript objects, strings, and floating-point numbers are garbage collected. These functions provide access to the garbage collector:

+ +

The rest of these APIs help protect objects from being destroyed by the garbage collector before the application is done using them.

+

If a variable is a root, then anything it points to will not be freed by the garbage collector. Failure to root objects is a very common cause of mysterious crashes.

+ +

Local root scopes are another way of protecting objects from the garbage collector.

+ +

{{ Jsapi_minversion_inline("1.8 (not yet released)") }} If an object contains references to other GC things that are not stored in SpiderMonkey data structures ("slots"), it must implement the JSTraceOp hook to enable the garbage collector to traverse those references. Otherwise the garbage collector will not find all reachable objects and may collect objects that are still reachable, leading to a crash. (In SpiderMonkey 1.7 and earlier, the JSMarkOp hook is used instead. This will be deprecated when SpiderMonkey 1.8 is released.)

+

The tracing APIs are used by the garbage collector and JSTraceOp hooks. JSAPI applications may also use them to examine the object graph. (For example, these APIs support very smooth integration between the JS garbage collector and other garbage collectors.)

+ +

Miscellaneous GC APIs:

+ +

Numbers

+ +

字符串

+ + +

Interning strings tells the SpiderMonkey engine to reuse existing string objects when possible.

+ +

The character data for external strings is stored in memory provided by the application. Applications can use this to avoid copying data back and forth between SpiderMonkey's heap and application memory.

+ +

对象

+ + +

属性

+

These functions correspond directly to the ways scripts access object properties:

+ +

The following functions are lower-level, allowing the JSAPI application more access to details of how properties are implemented. "Define" is a lower-level version of "set" that provides access to extra settings and does not call setters. Similarly, "lookup" is a lower-level version of "get" that offers extra options and does not call getters.

+ +

The following functions behave like JS_GetProperty except when operating on E4X XML objects.

+ +

A SpiderMonkey extension allows a native function to return an lvalue—that is, a reference to a property of an object:

+ +

A jsid is kind of like a jsval, only different. A handful of APIs use jsids instead of jsvals for property names: JS_CheckAccess, JS_Enumerate, JS_GetMethodById, and JS_NextProperty.

+ +

Classes

+

These API features are used to define custom classes—object types that are implemented in C/C++ code but accessible from JavaScript.

+ +

Adding native properties and methods to classes:

+ +

JSFastNative methods use these macros:

+ +

The behavior of a JSClass and its instances can be customized in many ways using callback functions.

+

JSClass method types:

+ +

JSExtendedClass method types:

+ +

JSObjectOps method types:

+ +

JSXMLObjectOps method types:

+ +

These stub functions can be used when creating a custom JSClass:

+ +

The behavior of a JSClass can be customized using these flags:

+ +

Arrays

+ + + +

Functions

+

Calling a function or a method of an object:

+ +

Function accessors:

+ +

Creating functions:

+ +

RegExps

+ +

Security

+ + +

Threading

+

The following functions support the SpiderMonkey threading model. They are only available in JS_THREADSAFE builds.

+ +

The following functions exist in all builds, but in non-JS_THREADSAFE builds, they do nothing:

+ +

Time

+ +

Callback Types

+

Native function types:

+ +

Other callback types:

+ +

See also Classes, above.

+

Macros

+ +

Preprocessor conditionals

+ +

These defines are useful for tuning SpiderMonkey performance:

+ +

C++ features

+ +

{{ languages( { "ja": "ja/JSAPI_Reference", "pl": "pl/Dokumentacja_JSAPI" } ) }}

+

JSAPI 参考

+

 

+

数据结构

+ diff --git a/files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/js_defineconstdoubles/index.html b/files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/js_defineconstdoubles/index.html new file mode 100644 index 0000000000..82835b714d --- /dev/null +++ b/files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/js_defineconstdoubles/index.html @@ -0,0 +1,59 @@ +--- +title: JS DefineConstDoubles +slug: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JS_DefineConstDoubles +translation_of: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JS_DefineConstDoubles +--- +

摘要

+

为对象创建一个或多个包含双浮点值的属性。

+

语法

+
  JSBool JS_DefineConstDoubles(JSContext *cx, JSObject *obj,
+    JSConstDoubleSpec *cds);
+
+ + + + + + + + + + + + + + + + + + + + + + + +
名称类型描述
cxJSContext *指向JS运行时信息内容的指针。
objJSObject *指向新建的属性的对象指针。
cdsJSConstDoubleSpec *指向创建的包含双浮点属性值和属性名的结构化数组的指针。最后一个数组元素必须包含一个为零值的成员。
+

描述

+

JS_DefineConstDoubles为特定的对象创建一个或多个成员变量,obj, 每个成员变量包含一个双浮点类型的值。每个成员变量在JSConstDoubleSpec结构中的flags字段被自动声名并由cds传递指针。 如果flags被设为0值, 成员变量的属性会自动被设为JSPROP_PERMANENT 或 JSPROP_READONLY

+

cds 是一个指向具有JSConstDoubleSpec结构的数组的第一个元素的指针。每个数组元素定义独立的变量名和变量值。数组的最后一个元素的name字段必须是0。JS_DefineConstDoubles为数组中的每一个名称字段不为零的元素建立一个成员变量。

+

通常情况下, JS_DefineConstDoubles 返回 JS_TRUE, 表明它在数组中已经建立了所有的属性列表。除此之外的情况下它返回JS_FALSE

+

更多参考

+ + + + + + + + + + + + + + + +
新闻组Functions
文档LXRSearch
章节 +

JSConstDoubleSpec, JS_DefineElement, JS_DefineFunction, JS_DefineFunctions, JS_DefineObject, JS_DefineProperties, JS_DefineProperty, JS_DefinePropertyWithTinyId

+
+

 

diff --git a/files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/js_doublecolon_call/index.html b/files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/js_doublecolon_call/index.html new file mode 100644 index 0000000000..a0c3d1239a --- /dev/null +++ b/files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/js_doublecolon_call/index.html @@ -0,0 +1,92 @@ +--- +title: 'JS::Call' +slug: 'Mozilla/Projects/SpiderMonkey/JSAPI_reference/JS::Call' +translation_of: 'Mozilla/Projects/SpiderMonkey/JSAPI_reference/JS::Call' +--- +
{{SpiderMonkeySidebar("JSAPI")}}
+ +
{{ jsapi_minversion_header("17") }}
+ + +
+

调用指定的JS函数。

+
+ +

句法

+ +
bool
+JS::Call(JSContext *cx, JS::HandleObject thisObj, JS::HandleFunction fun,
+         const JS::HandleValueArray &args, JS::MutableHandleValue rval);
+
+bool
+JS::Call(JSContext *cx, JS::HandleObject thisObj, const char *name,
+         const JS::HandleValueArray& args, JS::MutableHandleValue rval);
+
+bool
+JS::Call(JSContext *cx, JS::HandleObject thisObj, JS::HandleValue fun,
+         const JS::HandleValueArray& args, JS::MutableHandleValue rval);
+
+bool
+JS::Call(JSContext *cx, JS::HandleValue thisv, JS::HandleValue fun,
+         const JS::HandleValueArray& args, JS::MutableHandleValue rval);
+
+bool
+JS::Call(JSContext *cx, JS::HandleValue thisv, JS::HandleObject funObj,
+         const JS::HandleValueArray& args, JS::MutableHandleValue rval);
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
名称类型描述
cx{{jsapixref("JSRuntime", "JSContext *")}}指向JS上下文的指针,从中可以派生运行时信息。{{Jsapi-requires-request()}}
thisObj{{jsapixref("JSObject", "JS::HandleObject")}} / {{jsapixref("JS::Value", "JS::HandleValue")}}The "current" object on which the function operates; the object specified here is "this" when the function executes.
fun / funObj{{jsapixref("JSFunction", "JS::HandleFunction")}} / {{jsapixref("JS::Value", "JS::HandleValue")}} / {{jsapixref("JSObject", "JS::HandleObject")}}Pointer to the function to call. Should be a native function or JSAPI-compiled function.
nameconst char *Pointer to the function name to call.
args{{jsapixref("JS::HandleValueArray", "JS::HandleValueArray &")}}Arguments to pass to the function.
rval{{jsapixref("JS::Value", "JS::MutableHandleValue")}}Out parameter. On success, *rval receives the return value from the function call.
+ +

Description

+ +

JS::Callfun在对象上调用指定的函数thisObj在函数执行方面,该对象被视为this

+ +

有关更多详细信息,请参阅{{jsapixref("JS_CallFunction")}},{{jsapixref("JS_CallFunctionName")}}和{{jsapixref("JS_CallFunctionValue")}}。

+ +

也可以看看

+ + diff --git a/files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/js_doublecolon_ordinarytoprimitive/index.html b/files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/js_doublecolon_ordinarytoprimitive/index.html new file mode 100644 index 0000000000..b09164ee56 --- /dev/null +++ b/files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/js_doublecolon_ordinarytoprimitive/index.html @@ -0,0 +1,66 @@ +--- +title: 'JS::OrdinaryToPrimitive' +slug: 'Mozilla/Projects/SpiderMonkey/JSAPI_reference/JS::OrdinaryToPrimitive' +translation_of: 'Mozilla/Projects/SpiderMonkey/JSAPI_reference/JS::OrdinaryToPrimitive' +--- +
{{SpiderMonkeySidebar("JSAPI")}}
+ +

{{ jsapi_minversion_header("38") }}

+ +
+

将普通对象转换为原始值

+
+ +

语法说明

+ +
bool
+JS::OrdinaryToPrimitive(JSContext *cx, JS::HandleObject obj, JSType type,
+                        JS::MutableHandleValue vp);
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
名称类型描述
cx{{jsapixref("JSRuntime", "JSContext *")}}执行转换的上下文. {{ Jsapi-requires-request() }}
obj{{jsapixref("JSObject", "JS::HandleObject")}}要转换的对象。
type{{jsapixref("JSType")}}转换后值的类型。
vp{{jsapixref("JS::Value", "JS::MutableHandleValue")}}输出参数. 成功, *vp 收到转换后的值
+ +

描述

+ +

JS::OrdinaryToPrimitive 通过ES6 draft rev 28(2014年10月14日)7.1.1第二算法中指定的算法将JavaScript对象转换为指定的类型值。

+ +

Most users should not call this -- use {{jsapixref("JS::ToNumber")}}, {{jsapixref("JS::ToBoolean")}}, or {{jsapixref("JS::ToString")}} instead. This should only be called from custom convert hooks. It implements the default conversion behavior shared by most objects in JS, so it's useful as a fallback.

+ +

On success, JS::OrdinaryToPrimitive stores the converted value in *vp and returns true. On error or exception, it returns false, and the value left in *vp is undefined.

+ +

了解其他

+ + diff --git a/files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/js_evaluatescript/index.html b/files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/js_evaluatescript/index.html new file mode 100644 index 0000000000..94454ee794 --- /dev/null +++ b/files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/js_evaluatescript/index.html @@ -0,0 +1,69 @@ +--- +title: SpiderMonkey/JSAPI_参考/JS_EvaluateScript +slug: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JS_EvaluateScript +translation_of: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JS_EvaluateScript +--- +

编译并执行一个脚本。

+

语法

+
JSBool JS_EvaluateScript(JSContext *cx, JSObject *obj,
+    const char *src, uintN length, const char *filename,
+    uintN lineno, jsval *rval);
+
+JSBool JS_EvaluateUCScript(JSContext *cx, JSObject *obj,
+    const jschar *src, uintN length, const char *filename,
+    uintN lineno, jsval *rval);
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
名称数据类型描述
cxJSContext *脚本运行的上下文. {{ Jsapi-requires-request() }}
objJSObject *The scope in which to execute the script. This parameter is documented in detail at JS_ExecuteScript.
srcconst char * or const jschar *包含要编译和执行的脚本的字符串.
lengthuintNsrc的长度, in characters.
filenameconst char *Name of file or URL containing the script. Used to report filename or URL in error messages.
linenouintNLine number. Used to report the offending line in the file or URL if an error occurs.
rvaljsval *Out parameter. On success, *rval receives the value of the last-executed expression statement processed in the script.
+

描述

+

JS_EvaluateScript compiles and executes a script in the specified scope, obj. On successful completion, rval is a pointer to a variable that holds the value from the last executed expression statement processed in the script. JS_EvaluateUCScript is the Unicode version of the function.

+

src is the string containing the text of the script. length indicates the size of the text version of the script in characters.

+

filename is the name of the file (or URL) containing the script. This information is used in messages if an error occurs during compilation. Similarly, lineno is used to report the line number of the script or file where an error occurred during compilation.

+

If a script compiles and executes successfully, *rval receives the value from the last-executed expression statement in the script, and JS_EvaluateScript or JS_EvaluateUCScript returns JS_TRUE. Otherwise it returns JS_FALSE and the value left in *rval is undefined.

+

See Also

+

{{ LXRSearch("ident", "i", "JS_EvaluateScript") }}
+ {{ LXRSearch("ident", "i", "JS_EvaluateUCScript") }}

+

JS_CompileFile, JS_CompileScript, JS_DecompileScript, JS_DestroyScript, JS_EvaluateScriptForPrincipals

+

{{ languages( { "ja": "ja/JS_EvaluateScript" } ) }}

diff --git a/files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/js_getversion/index.html b/files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/js_getversion/index.html new file mode 100644 index 0000000000..a2b2888958 --- /dev/null +++ b/files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/js_getversion/index.html @@ -0,0 +1,29 @@ +--- +title: SpiderMonkey/JSAPI_参考/JS_GetVersion +slug: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JS_GetVersion +translation_of: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JS_GetVersion +--- +

Retrieves the JavaScript version number used within a specified executable script context.

+

语法

+
JSVersion JS_GetVersion(JSContext *cx);
+
+ + + + + + + + + + + + + +
参数名称类型描述
cxJSContext *要查询的上下文.
+

描述

+

JS_GetVersion returns the JavaScript version currently used by the given JSContext, cx. The result is one of the JSVersion constants.

+

When a context is created, its version is initially JSVERSION_DEFAULT. Scripts are compiled using the latest version of the JavaScript language. To configure a context to run scripts using a specific version of JavaScript, use JS_SetVersion.

+

请参阅

+

{{ LXRSearch("ident", "i", "JS_GetVersion") }}

+

JS_VersionToString, JS_StringToVersion

diff --git a/files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/js_hasownproperty/index.html b/files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/js_hasownproperty/index.html new file mode 100644 index 0000000000..ed6e760796 --- /dev/null +++ b/files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/js_hasownproperty/index.html @@ -0,0 +1,73 @@ +--- +title: JS_HasOwnProperty +slug: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JS_HasOwnProperty +tags: + - 中文 +translation_of: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JS_HasOwnProperty +--- +
{{SpiderMonkeySidebar("JSAPI")}}
+ +

{{ jsapi_minversion_header("45") }}

+ +
+

Determine whether a JavaScript object has a specified own property.

+
+ +

Syntax

+ +
bool
+JS_HasOwnProperty(JSContext* cx, HandleObject obj, const char* name,
+                  bool* foundp)
+
+bool
+JS_HasOwnPropertyById(JSContext* cx, HandleObject obj, HandleId id,
+                      bool* foundp)
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
NameTypeDescription
cx{{jsapixref("JSRuntime", "JSContext *")}}A context. {{ Jsapi-requires-request() }}
obj{{jsapixref("JSObject", "JS::HandleObject")}}Object to search on for the property.
name or idconst char * or {{jsapixref("jsid", "JS::HandleId")}}Name of the property to look up.
foundpbool *Non-null pointer to a variable of type bool. On success, JS_HasOwnProperty stores true in this variable if obj has an own property with the given name, and false if not.
+ +

Description

+ +

JS_HasOwnProperty searches an object, obj, for an own property with the specified name. It behaves like the JavaScript expression Object.hasOwnProperty(obj, name). JS_HasOwnPropertyById is the same but takes a {{jsapixref("jsid", "JS::HandleId")}} for the property name.

+ +

If the property exists, this function sets *foundp to true and returns true.

+ +

If the object obj has no such property, the function sets *foundp to false and returns true (to indicate that no error occurred).

+ +

If an error occurs during the search, the function returns false, and the value of *foundp is undefined.

+ +

See Also

+ + diff --git a/files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/js_newruntime/index.html b/files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/js_newruntime/index.html new file mode 100644 index 0000000000..885bb3dd6e --- /dev/null +++ b/files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/js_newruntime/index.html @@ -0,0 +1,33 @@ +--- +title: JS_NewRuntime +slug: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JS_NewRuntime +tags: + - JSAPI_Reference + - SpiderMonkey +translation_of: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JS_NewRuntime +--- +

Initializes the JavaScript runtime.

+

Syntax

+
JSRuntime * JS_NewRuntime(uint32 maxbytes);
+
+ + + + + + + + + + + + + +
NameTypeDescription
maxbytesuint32Maximum number of allocated bytes after which garbage collection is run.
+

Description

+

JS_NewRuntime initializes the JavaScript runtime environment. Call JS_NewRuntime before making any other API calls. JS_NewRuntime allocates memory for the JSRuntime and initializes certain internal runtime structures. maxbytes specifies the number of allocated bytes after which garbage collection is run.

+

Generally speaking, most applications need only one JSRuntime. In a JS_THREADSAFE build, each runtime is capable of handling multiple execution threads, using one JSContext per thread, sharing the same JSRuntime. You only need multiple runtimes if your application requires completely separate JS engines that cannot share values, objects, and functions.

+

On success, JS_NewRuntime returns a pointer to the newly created runtime, which the caller must later destroy using JS_DestroyRuntime. Otherwise it returns NULL.

+

Notes

+

Ordinarily, JS_NewRuntime should be the first JSAPI call in an application, and JS_DestroyRuntime and JS_ShutDown should be the last ones.

+

{{ LXRSearch("ident", "i", "JS_NewRuntime") }}

diff --git a/files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/js_seterrorreporter/index.html b/files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/js_seterrorreporter/index.html new file mode 100644 index 0000000000..e04127a541 --- /dev/null +++ b/files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/js_seterrorreporter/index.html @@ -0,0 +1,61 @@ +--- +title: SpiderMonkey/JSAPI_参考/JS_SetErrorReporter +slug: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JS_SetErrorReporter +translation_of: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JS_SetErrorReporter +--- +

指定一个程序的错误报告途径.

+

语法

+
JSErrorReporter JS_SetErrorReporter(JSContext *cx, JSErrorReporter er);
+
+ + + + + + + + + + + + + + + + + + +
形式参数类型描述
cxJSContext *Pointer to a JS context from which to derive runtime information.
erJSErrorReporter在你的程序中用于报告错误的自定义函数, 见下面的描述.
+

  回调函数语法

+
typedef void (*JSErrorReporter)(
+    JSContext *cx, const char *message, JSErrorReport *report);
+
+ + + + + + + + + + + + + + + + + + + + + + + +
形式参数类型描述
cxJSContext *错误发生的上下文。
messageconst char *一个错误信息。
reportJSErrorReport *一个包含错误额外的详细资料报告记录。
+

描述

+

JS_SetErrorReporter enables you to define and use your own error reporting mechanism in your applications. The reporter you define is automatically passed a JSErrorReport structure when an error occurs and has been parsed by JS_ReportError.

+

Typically, the error reporting mechanism you define should log the error where appropriate (such as to a log file), and display an error to the user of your application. The error you log and display can make use of the information passed about the error condition in the JSErrorReport structure.

+

Like all other SpiderMonkey callbacks, the error reporter callback must not throw a C++ exception.

+

{{ LXRSearch("ident", "i", "JS_SetErrorReporter") }}

diff --git a/files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/js_valuetostring/index.html b/files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/js_valuetostring/index.html new file mode 100644 index 0000000000..ab0e6654a4 --- /dev/null +++ b/files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/js_valuetostring/index.html @@ -0,0 +1,45 @@ +--- +title: SpiderMonkey/JSAPI_参考/JS_ValueToString +slug: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JS_ValueToString +translation_of: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JS_ValueToString +--- +

把一个jsval值 转换成一个 JSString.

+ +

 

+ +

语法

+ +
JSString * JS_ValueToString(JSContext *cx, jsval v);
+
+ + + + + + + + + + + + + + + + + + + +
NameTypeDescription
cxJSContext *The context in which to perform the conversion. {{ Jsapi-requires-request() }}
vjsval转换的jsval值.
+ +

描述

+ +

JS_ValueToString converts a specified JS value, v, to a JS string. It implements the ToString operator specified in ECMA 262-3 §9. If v is an object, the actual conversion is performed by its JSClass.convert callback, which may call the JavaScript methods v.toString() and/or v.valueOf(). On success, JS_ValueToString returns a pointer to a string. On error or exception, it returns NULL. This happens, for example, if v is an object and v.toString() throws an exception.

+ +

The resulting JSString is subject to garbage collection unless you protect it using a local root, an object property, or the JS_AddRoot function.

+ +

See Also

+ +

{{ LXRSearch("ident", "i", "JS_ValueToString") }}

+ +

JS_ConvertArguments, JS_ConvertValue, JS_GetTypeName, JS_TypeOfValue, JS_ValueToBoolean, JS_ValueToFunction, JS_ValueToInt32, JS_ValueToNumber, JS_ValueToObject

diff --git a/files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/jsclass/index.html b/files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/jsclass/index.html new file mode 100644 index 0000000000..dd119aba3f --- /dev/null +++ b/files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/jsclass/index.html @@ -0,0 +1,137 @@ +--- +title: JSClass +slug: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JSClass +translation_of: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JSClass +--- +

摘要

+

数据结构 定义一个基本类用于建立和维护JS对象。

+

语法

+
struct JSClass {
+    char *name;
+    uint32 flags;
+    /* Mandatory non-null function pointer members. */
+    JSPropertyOp addProperty;
+    JSPropertyOp delProperty;
+    JSPropertyOp getProperty;
+    JSPropertyOp setProperty;
+    JSEnumerateOp enumerate;
+    JSResolveOp resolve;
+    JSConvertOp convert;
+    JSFinalizeOp finalize;
+    /* Optionally non-null members start here. */
+    JSGetObjectOps getObjectOps;
+    JSCheckAccessOp checkAccess;
+    JSNative call;
+    JSNative construct;
+    JSXDRObjectOp xdrObject;
+    JSHasInstanceOp hasInstance;
+    JSMarkOp mark;
+    JSReserveSlotsOp reserveSlots;
+};
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
名称类型描述
namechar *类名
flagsuint32类的属性(成员变量)。0表明属性不是一个集合. 属性值可以是下面这些值中的一个或多个: + +
addPropertyJSPropertyOp为类增加属性的函数。
delPropertyJSPropertyOp从类中删除属性的函数。
getPropertyJSPropertyOp获取属性值的函数。
setPropertyJSPropertyOp设置属性值的函数
enumerateJSEnumerateOp枚举类所有属性的函数。
resolveJSResolveOpMethod for resolving property ambiguities.
convertJSConvertOp进行属性值转换的函数。
finalizeJSFinalizeOp将类设为不可修改(finalizing)的函数。
getObjectOpsJSGetObjectOps为类定义重载方法指向一个可选的结构。如果你不想重载类的默认方法,可以将getObjectOps 设为 NULL
checkAccessJSCheckAccessOp为类或对象操作结构指定可选的自定义请求控制方法。如果你不想提供自定义的请求控制,设置此值为NULL
callJSNative为对象提供替换这个类的方法。
constructJSNative为对象提供方法去替换这个类的构造器。
xdrObjectJSXDRObjectOp指向一个可选的XDR对象和它的方法。如果你不想使用XDR, 设置这个值为 NULL
hasInstanceJSHasInstanceOpPointer to an optional hasInstance method for this object. If you do not provide a method for hasInstance, set this pointer to NULL.
markJSMarkOpPointer to an optional mark method for this object. If you do not provide a method for mark, set this pointer to NULL.
reserveSlotsJSReserveSlotsOpPointer to an optional reserveSlots method for this object. If you do not provide a method for reserveSlots, set this pointer to NULL.
+

 

diff --git a/files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/jsconstdoublespec/index.html b/files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/jsconstdoublespec/index.html new file mode 100644 index 0000000000..509d3b12ed --- /dev/null +++ b/files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/jsconstdoublespec/index.html @@ -0,0 +1,56 @@ +--- +title: JSConstDoubleSpec +slug: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JSConstDoubleSpec +translation_of: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JSConstDoubleSpec +--- +

摘要

+

数据结构

+

定义一个双浮点类型的变量并进行赋值。

+

语法

+
struct JSConstDoubleSpec {
+    jsdouble dval;
+    const char *name;
+    uint8 flags;
+    uint8 spare[3];
+};
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
名称类型描述
dvaljsdouble双浮点类型的值。
nameconst char *给双浮点类型定义的名称。
flagsuint8双浮点类型的属性。这里可以是0或者是下面这些值之中的一个: + +
spareuint8{{ mediawiki.external(3) }}为以后的扩展保留的属性。
+

描述

+

JS双浮点型的构造规范 典型应用于定义一个双浮点值集合,并使用JS_DefineConstDoubles对生成的对象进行赋值。使用JS_DefineConstDouble为指定的对象创建一个或多个双浮点类型属性。

+

JS_DefineConstDoubles为一类由JSConstDoubleSpecs定义的数组提供证明。为每个数据元素定义独立的属性名和设置独立的属性值。数组的最后一个元素必须包括0值(zero-valued)的属性。JS_DefineConstDoubles 为数组中每个非0值(non-zero)元素创建一个属性值。

diff --git a/files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/jserrorreport/index.html b/files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/jserrorreport/index.html new file mode 100644 index 0000000000..7246c3c416 --- /dev/null +++ b/files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/jserrorreport/index.html @@ -0,0 +1,6 @@ +--- +title: JSErrorReport +slug: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JSErrorReport +translation_of: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JSErrorReport +--- +

Media:Example.ogg

diff --git a/files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/jsproperty/index.html b/files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/jsproperty/index.html new file mode 100644 index 0000000000..16f0cca090 --- /dev/null +++ b/files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/jsproperty/index.html @@ -0,0 +1,29 @@ +--- +title: JSProperty +slug: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JSProperty +translation_of: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JSProperty +--- +
{{SpiderMonkeySidebar("JSAPI")}}
+ +

{{deprecated_header("jsapi16")}}

+ +
+

限内部使用。{{jsapixref("JSObjectOps")}}层使用的JavaScript对象属性的类型。

+
+ +

语法

+ +
struct JSProperty {
+    jsid id;
+};
+
+ +

Description

+ +

JSProperty 是所有对象属性的抽象基类。 它在 {{jsapixref("JSObjectOps.lookupProperty")}}, {{jsapixref("JSObjectOps.getAttributes", "getAttributes")}}, {{jsapixref("JSObjectOps.getAttributes", "setAttributes")}}, 和 {{jsapixref("JSObjectOps.dropProperty", "dropProperty")}}中内部使用。

+ +

See Also

+ + diff --git a/files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/jspropertydescriptor/index.html b/files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/jspropertydescriptor/index.html new file mode 100644 index 0000000000..9f35d49fdb --- /dev/null +++ b/files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/jspropertydescriptor/index.html @@ -0,0 +1,69 @@ +--- +title: JSPropertyDescriptor +slug: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JSPropertyDescriptor +translation_of: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JSPropertyDescriptor +--- +
{{SpiderMonkeySidebar("JSAPI")}}
+ +
描述符是一个用于声明一个属性是否可以被修改,是否可以被删除,是否可以被枚举的一个对象
+ +

内容

+ +

每一个属性只拥有一个描述符对象,但是这个对象中拥有多个键值,用来描述这个属性,下表说明了描述符中可以拥有的键值.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Field NameDescription
getterget 语法为属性绑定一个函数,每当查询该属性时便调用对应的函数,查询的结构为该函数的返回值
setter如果试着改变一个属性的值,那么对应的 setter 函数将被执行
value描述指定属性的值 , 可以是任何有效的 Javascript 值(函数 , 对象 , 字符串 ...).
configurable当且仅当该属性的 configurable 为 true 时,该属性 描述符 才能够被改变, 同时该属性也能从对应的对象上被删除.
enumerable描述指定的属性是否是 可枚举 的.
writable当且仅当该属性的 writabletrue 时, value 才能被赋值运算符改变。
+ +

描述

+ +

描述符 是描述对象属性的属性 , 对象里目前存在的属性描述符有两种主要形式:数据描述符 存取描述符. 可以通过 Object.getOwnPropertyDescriptor() 函数来获取某个对象下指定属性的对应的 描述符 .

+ +

示例

+ +

下面将演示通过 Object.defineProperty() 函数定义一个对象的属性.

+ +
var language = {}; // 定义一个空对象 language
+
+Object.defineProperty(language, 'log', { // 定义 language 对象下的 log 属性
+    value : ['CN','EN'],
+    writable : true,
+    enumerable : true,
+    configurable : true
+})
+ +

此时这是一个可读可写可枚举的属性 此时我们将这三个值都设为了 true 此时上面这段代码等价于:

+ +
var language = {}; // 定义一个空对象 language
+
+languange.log = ['CN','EN']; // 定义 language 对象下的 log 属性
+
diff --git a/files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/jsruntime/index.html b/files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/jsruntime/index.html new file mode 100644 index 0000000000..daabc3f876 --- /dev/null +++ b/files/zh-cn/mozilla/projects/spidermonkey/jsapi_reference/jsruntime/index.html @@ -0,0 +1,29 @@ +--- +title: JSRuntime +slug: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JSRuntime +translation_of: Mozilla/Projects/SpiderMonkey/JSAPI_reference/JSRuntime +--- +
{{SpiderMonkeySidebar("JSAPI")}}
+ +
+

在JSAPI中,JSRuntime是代表JavaScript引擎实例的顶级对象。一个程序通常只有一个JSRuntime,即使它有很多线程。JSRuntime是JavaScript对象所居住的世界;他们不能去其他人JSRuntime

+ +

所有JavaScript代码和大多数JSAPI调用都在内运行JSContextJSContext是对一个孩子JSRuntime上下文可以运行脚本。它包含全局对象和执行堆栈。异常处理错误报告和某些语言选项是基于Per-的JSContext创建上下文后,可以将上下文多次用于不同的脚本或JSAPI查询。例如,浏览器可能会为每个HTML页面创建一个单独的上下文。页面中的每个脚本都可以使用相同的上下文。

+ +

对象在同一个 JSRuntimeJSContext之间可以共享。对象与创建对象的上下文之间没有固定的关联。

+ +

设置和拆卸a JSRuntime和a的示例代码JSContextJSAPI用户指南中

+
+ +

线程

+ +

只有一个线程可以使用JSContext JSRuntime较早的版本允许使用  JS_ClearContextThread 和其他功能将a JSContext 从一个线程移动  到另一个线程。此功能已被删除。

+ +

相关文档

+ + diff --git a/files/zh-cn/mozilla/projects/spidermonkey/parser_api/index.html b/files/zh-cn/mozilla/projects/spidermonkey/parser_api/index.html new file mode 100644 index 0000000000..03b00c9b00 --- /dev/null +++ b/files/zh-cn/mozilla/projects/spidermonkey/parser_api/index.html @@ -0,0 +1,1625 @@ +--- +title: Parser API +slug: Mozilla/Projects/SpiderMonkey/Parser_API +translation_of: Mozilla/Projects/SpiderMonkey/Parser_API +--- +

{{ jsapi_minversion_header("1.8.5") }}

+ +

最近构建的独立的SpiderMonkey shell包含了SpiderMonkey解析器的反射,可以通过JavaScript API来访问. 这使得我们更容易的用JavaScript写出处理JavaScript源代码的工具, 比如语法高亮工具,静态分析工具, 翻译器,编译器,混淆器等等.

+ +

例子:

+ +
> var expr = Reflect.parse("obj.foo + 42").body[0].expression
+> expr.left.property
+({loc:null, type:"Identifier", name:"foo"})
+> expr.right
+({loc:{source:null, start:{line:1, column:10}, end:{line:1, column:12}}, type:"Literal", value:42})
+
+ +

Reflect也可以使用在Firefox 7及以上版本中,但必须要导入一个模块:

+ +
Components.utils.import("resource://gre/modules/reflect.jsm")
+
+ +

如果不想用Reflect全局对象,也可以指定一个对象名称:

+ +
Components.utils.import("resource://gre/modules/reflect.jsm", obj)
+
+ +

内置对象

+ +

无论是SpiderMonkey shell还是Firefox (导入模块之后),全局对象Reflect目前都只有一个parse方法.

+ +

Reflect对象的属性

+ +

Reflect对象目前只有一个方法.

+ +

Reflect.parse(src[, options])

+ +

将SRC强制转为字符串,并将结果作为javascript程序进行分析。默认情况下,解析返回一个表示被解析的抽象语法树(AST)的程序对象(见下文)

+ +

可通过options对象提供其他选项, 可以使用的属性如下:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
locBooleanDefault: true
如果loctrue,则解析器会在返回的AST节点中包含上源码的位置信息.
sourceStringDefault: null
A description of the input source; typically a filename, path, or URL. This string is not meaningful to the parsing process, but is produced as part of the source location information in the returned AST nodes.
lineNumberDefault: 1
初始行号,用在源码位置信息上.
builderBuilderDefault: null
+

A builder object, which can be used to produce AST nodes in custom data formats. The expected callback methods are described under Builder Objects.

+
+ +

If parsing fails due to a syntax error, an instance of SyntaxError is thrown. The syntax error object thrown by Reflect.parse() has the same message property as the syntax error that would be thrown by eval(src). The lineNumber and fileName properties of the syntax error object indicate the source location of the syntax error.

+ +

节点对象

+ +

默认情况下, Reflect.parse() 生成Node对象, 即普通的JavaScript对象 (i.e., 它们的原型来自标准的Object原型). 所有的节点类型都实现了以下的接口:

+ +
interface Node {
+    type: string;
+    loc: SourceLocation | null;
+}
+
+ +

type 字段是一个字符串,代表AST变量类型.节点的每个子类型在下面的文档中都用其  type 字段特定的字符串标注出来了. 你可以使用这个字段去决定一个节点要实现的接口.

+ +

loc 字段代表节点的源位置信息. 如果解析器未生成有关节点的源位置信息,  null 字段为空;否则它是一个对象, 包括一个起始位置 (the position of the first character of the parsed source region) 和一个结束位置 (the position of the first character after the parsed source region):ss

+ +
interface SourceLocation {
+    source: string | null;
+    start: Position;
+    end: Position;
+}
+
+ +

每个 Position 包括一个 line 数字 (1-indexed) 和 column 数字 (0-indexed):

+ +
interface Position {
+    line: uint32 >= 1;
+    column: uint32 >= 0;
+}
+ +

Programs

+ +
interface Program <: Node {
+    type: "Program";
+    body: [ Statement ];
+}
+
+ +

A complete program source tree.

+ +

函数

+ +
interface Function <: Node {
+    id: Identifier | null;
+    params: [ Pattern ];
+    defaults: [ Expression ];
+    rest: Identifier | null;
+    body: BlockStatement | Expression;
+    generator: boolean;
+    expression: boolean;
+}
+
+ +

A function declaration or expression. The body of the function may be a block statement, or in the case of an expression closure, an expression.

+ +
注: Expression closures 是SpiderMonkey特有的.
+ +

If the generator flag is true, the function is a generator function, i.e., contains a yield expression in its body (other than in a nested function).

+ +
注: Generators 是SpiderMonkey特有的.
+ +

If the expression flag is true, the function is an expression closure and the body field is an expression.

+ +

语句

+ +
interface Statement <: Node { }
+
+ +

任意语句.

+ +
interface EmptyStatement <: Statement {
+    type: "EmptyStatement";
+}
+
+ +

一个空语句,也就是,一个孤立的分号.

+ +
interface BlockStatement <: Statement {
+    type: "BlockStatement";
+    body: [ Statement ];
+}
+
+ +

一个语句块,也就是由大括号包围的语句序列.

+ +
interface ExpressionStatement <: Statement {
+    type: "ExpressionStatement";
+    expression: Expression;
+}
+
+ +

一个表达式语句,也就是,仅有一个表达式组成的语句.

+ +
interface IfStatement <: Statement {
+    type: "IfStatement";
+    test: Expression;
+    consequent: Statement;
+    alternate: Statement | null;
+}
+
+ +

一个if语句.

+ +
interface LabeledStatement <: Statement {
+    type: "LabeledStatement";
+    label: Identifier;
+    body: Statement;
+}
+
+ +

一个标签语句,也就是, a statement prefixed by a break/continue label.

+ +
interface BreakStatement <: Statement {
+    type: "BreakStatement";
+    label: Identifier | null;
+}
+
+ +

一个break语句.

+ +
interface ContinueStatement <: Statement {
+    type: "ContinueStatement";
+    label: Identifier | null;
+}
+
+ +

一个continue语句.

+ +
interface WithStatement <: Statement {
+    type: "WithStatement";
+    object: Expression;
+    body: Statement;
+}
+
+ +

with statement.

+ +
interface SwitchStatement <: Statement {
+    type: "SwitchStatement";
+    discriminant: Expression;
+    cases: [ SwitchCase ];
+    lexical: boolean;
+}
+
+ +

一个switch语句. The lexical flag is metadata indicating whether the switch statement contains any unnested let declarations (and therefore introduces a new lexical scope).

+ +
interface ReturnStatement <: Statement {
+    type: "ReturnStatement";
+    argument: Expression | null;
+}
+
+ +

一个return语句.

+ +
interface ThrowStatement <: Statement {
+    type: "ThrowStatement";
+    argument: Expression;
+}
+
+ +

一个throw语句.

+ +
interface TryStatement <: Statement {
+    type: "TryStatement";
+    block: BlockStatement;
+    handlers: [ CatchClause ];
+    finalizer: BlockStatement | null;
+}
+
+ +

一个try语句.

+ +
注: 多个catch子句是SpiderMonkey特有的.
+ +
interface WhileStatement <: Statement {
+    type: "WhileStatement";
+    test: Expression;
+    body: Statement;
+}
+
+ +

一个while语句.

+ +
interface DoWhileStatement <: Statement {
+    type: "DoWhileStatement";
+    body: Statement;
+    test: Expression;
+}
+
+ +

一个do/while语句.

+ +
interface ForStatement <: Statement {
+    type: "ForStatement";
+    init: VariableDeclaration | Expression | null;
+    test: Expression | null;
+    update: Expression | null;
+    body: Statement;
+}
+
+ +

一个for语句.

+ +
interface ForInStatement <: Statement {
+    type: "ForInStatement";
+    left: VariableDeclaration |  Expression;
+    right: Expression;
+    body: Statement;
+    each: boolean;
+}
+
+ +

一个for/in语句, or, if each is true, a for each/in statement.

+ +
注: for each语法是SpiderMonkey特有的.
+ +
interface LetStatement <: Statement {
+    type: "LetStatement";
+    head: [ { id: Pattern, init: Expression | null } ];
+    body: Statement;
+}
+
+ +

一个let语句.

+ +
注: let语句形式是SpiderMonkey特有的.
+ +
interface DebuggerStatement <: Statement {
+    type: "DebuggerStatement";
+}
+
+ +

一个debugger语句.

+ +
注: debugger语句是ECMAScript 5中的新语法,尽管SpiderMonkey已经支持它很多年了.
+ +

声明

+ +
interface Declaration <: Statement { }
+
+ +

Any declaration node. Note that declarations are considered statements; this is because declarations can appear in any statement context in the language recognized by the SpiderMonkey parser.

+ +
注: 任意嵌套作用域下的声明是SpiderMonkey特有的.
+ +
interface FunctionDeclaration <: Function, Declaration {
+    type: "FunctionDeclaration";
+    id: Identifier;
+    params: [ Pattern ];
+    defaults: [ Expression ];
+    rest: Identifier | null;
+    body: BlockStatement | Expression;
+    generator: boolean;
+    expression: boolean;
+}
+
+ +

一个函数声明.

+ +
注: id字段不能为null.
+ +
interface VariableDeclaration <: Declaration {
+    type: "VariableDeclaration";
+    declarations: [ VariableDeclarator ];
+    kind: "var" | "let" | "const";
+}
+
+ +

一个变量声明,可以通过var, let, 或const.

+ +
interface VariableDeclarator <: Node {
+    type: "VariableDeclarator";
+    id: Pattern;
+    init: Expression | null;
+}
+
+ +

一个变量声明符.

+ +
注: id字段不能为null.
+ +
注: letconst是SpiderMonkey特有的.
+ +

表达式

+ +
interface Expression <: Node, Pattern { }
+ +

任意表达式节点. Since the left-hand side of an assignment may be any expression in general, an expression can also be a pattern.

+ +
interface ThisExpression <: Expression {
+    type: "ThisExpression";
+}
+
+ +

一个this表达式.

+ +
interface ArrayExpression <: Expression {
+    type: "ArrayExpression";
+    elements: [ Expression | null ];
+}
+ +

一个数组表达式.

+ +
interface ObjectExpression <: Expression {
+    type: "ObjectExpression";
+    properties: [ { key: Literal | Identifier,
+                    value: Expression,
+                    kind: "init" | "get" | "set" } ];
+}
+ +

一个对象表达式. A literal property in an object expression can have either a string or number as its value. Ordinary property initializers have a kind value "init"; getters and setters have the kind values "get" and "set", respectively.

+ +
interface FunctionExpression <: Function, Expression {
+    type: "FunctionExpression";
+    id: Identifier | null;
+    params: [ Pattern ];
+    defaults: [ Expression ];
+    rest: Identifier | null;
+    body: BlockStatement | Expression;
+    generator: boolean;
+    expression: boolean;
+}
+
+ +

一个函数表达式.

+ +
interface SequenceExpression <: Expression {
+    type: "SequenceExpression";
+    expressions: [ Expression ];
+}
+ +

一个序列表达式,也就是一个由逗号分割的表达式序列.

+ +
interface UnaryExpression <: Expression {
+    type: "UnaryExpression";
+    operator: UnaryOperator;
+    prefix: boolean;
+    argument: Expression;
+}
+ +

A unary operator expression.

+ +
interface BinaryExpression <: Expression {
+    type: "BinaryExpression";
+    operator: BinaryOperator;
+    left: Expression;
+    right: Expression;
+}
+ +

一个二元运算符表达式.

+ +
interface AssignmentExpression <: Expression {
+    type: "AssignmentExpression";
+    operator: AssignmentOperator;
+    left: Expression;
+    right: Expression;
+}
+ +

An assignment operator expression.

+ +
interface UpdateExpression <: Expression {
+    type: "UpdateExpression";
+    operator: UpdateOperator;
+    argument: Expression;
+    prefix: boolean;
+}
+ +

An update (increment or decrement) operator expression.

+ +
interface LogicalExpression <: Expression {
+    type: "LogicalExpression";
+    operator: LogicalOperator;
+    left: Expression;
+    right: Expression;
+}
+ +

一个逻辑运算符表达式.

+ +
interface ConditionalExpression <: Expression {
+    type: "ConditionalExpression";
+    test: Expression;
+    alternate: Expression;
+    consequent: Expression;
+}
+ +

一个条件运算符表达式, i.e., a ternary ?/: expression.

+ +
interface NewExpression <: Expression {
+    type: "NewExpression";
+    callee: Expression;
+    arguments: [ Expression ] | null;
+}
+ +

A new expression.

+ +
interface CallExpression <: Expression {
+    type: "CallExpression";
+    callee: Expression;
+    arguments: [ Expression ];
+}
+ +

A function or method call expression.

+ +
interface MemberExpression <: Expression {
+    type: "MemberExpression";
+    object: Expression;
+    property: Identifier | Expression;
+    computed : boolean;
+}
+ +

一个member表达式. If computed === true, the node corresponds to a computed e1[e2] expression and property is an Expression. If computed === false, the node corresponds to a static e1.x expression and property is an Identifier.

+ +
interface YieldExpression <: Expression {
+    argument: Expression | null;
+}
+
+ +

yield expression.

+ +
注: yield expressions 是SpiderMonkey特有的.
+ +
interface ComprehensionExpression <: Expression {
+    body: Expression;
+    blocks: [ ComprehensionBlock ];
+    filter: Expression | null;
+}
+
+ +

An array comprehension. The blocks array corresponds to the sequence of for and for each blocks. The optional filter expression corresponds to the final if clause, if present.

+ +
注: Array comprehensions 是SpiderMonkey特有的.
+ +
interface GeneratorExpression <: Expression {
+    body: Expression;
+    blocks: [ ComprehensionBlock ];
+    filter: Expression | null;
+}
+
+ +

A generator expression. As with array comprehensions, the blocks array corresponds to the sequence of for and for each blocks, and the optional filter expression corresponds to the final if clause, if present.

+ +
注: Generator expressions 是SpiderMonkey特有的.
+ +
interface GraphExpression <: Expression {
+    index: uint32;
+    expression: Literal;
+}
+
+ +

graph expression, aka "sharp literal," such as #1={ self: #1# }.

+ +
注: Graph expressions 是SpiderMonkey特有的.
+ +
interface GraphIndexExpression <: Expression {
+    index: uint32;
+}
+
+ +

一个graph索引表达式,又称为"井号变量",比如#1#.

+ +
注: Graph索引表达式
+ +
Graph索引表达式是SpiderMonkey特有的.
+ +
interface LetExpression <: Expression {
+    type: "LetExpression";
+    head: [ { id: Pattern, init: Expression | null } ];
+    body: Expression;
+}
+
+ +

一个let表达式.

+ +
注: let表达式是SpiderMonkey特有的.
+ +

模式

+ +
interface Pattern <: Node { }
+
+ +

JavaScript 1.7 introduced destructuring assignment and binding forms. All binding forms (such as function parameters, variable declarations, and catch block headers), accept array and object destructuring patterns in addition to plain identifiers. The left-hand sides of assignment expressions can be arbitrary expressions, but in the case where the expression is an object or array literal, it is interpreted by SpiderMonkey as a destructuring pattern.

+ +

Since the left-hand side of an assignment can in general be any expression, in an assignment context, a pattern can be any expression. In binding positions (such as function parameters, variable declarations, and catch headers), patterns can only be identifiers in the base case, not arbitrary expressions.

+ +
interface ObjectPattern <: Pattern {
+    type: "ObjectPattern";
+    properties: [ { key: Literal | Identifier, value: Pattern } ];
+}
+
+ +

An object-destructuring pattern. A literal property in an object pattern can have either a string or number as its value.

+ +
interface ArrayPattern <: Pattern {
+    type: "ArrayPattern";
+    elements: [ Pattern | null ];
+}
+
+ +

An array-destructuring pattern.

+ +

子句

+ +
interface SwitchCase <: Node {
+    type: "SwitchCase";
+    test: Expression | null;
+    consequent: [ Statement ];
+}
+
+ +

一个case (if test is an Expression) or default (if test === null) clause in the body of a switch语句.

+ +
interface CatchClause <: Node {
+    type: "CatchClause";
+    param: Pattern;
+    guard: Expression | null;
+    body: BlockStatement;
+}
+
+ +

catch clause following a try block. The optional guard property corresponds to the optional expression guard on the bound variable.

+ +
注: The guard expression is SpiderMonkey-specific.
+ +
interface ComprehensionBlock <: Node {
+    left: Pattern;
+    right: Expression;
+    each: boolean;
+}
+
+ +

for or for each block in an array comprehension or generator expression.

+ +
注: Array comprehensions and generator expressions 是SpiderMonkey特有的.
+ +

杂项

+ +
interface Identifier <: Node, Expression, Pattern {
+    type: "Identifier";
+    name: string;
+}
+
+ +

An identifier. Note that an identifier may be an expression or a destructuring pattern.

+ +
interface Literal <: Node, Expression {
+    type: "Literal";
+    value: string | boolean | null | number | RegExp;
+}
+
+ +

A literal token. Note that a literal can be an expression.

+ +
enum UnaryOperator {
+    "-" | "+" | "!" | "~" | "typeof" | "void" | "delete"
+}
+
+ +

A unary operator token.

+ +
enum BinaryOperator {
+    "==" | "!=" | "===" | "!=="
+         | "<" | "<=" | ">" | ">="
+         | "<<" | ">>" | ">>>"
+         | "+" | "-" | "*" | "/" | "%"
+         | "|" | "^" | "in"
+         | "instanceof" | ".."
+}
+
+ +

A binary operator token.

+ +
注: The .. operator is E4X-specific.
+ +
enum LogicalOperator {
+    "||" | "&&"
+}
+
+ +

A logical operator token.

+ +
enum AssignmentOperator {
+    "=" | "+=" | "-=" | "*=" | "/=" | "%="
+        | "<<=" | ">>=" | ">>>="
+        | "|=" | "^=" | "&="
+}
+
+ +

An assignment operator token.

+ +
enum UpdateOperator {
+    "++" | "--"
+}
+
+ +

An update (increment or decrement) operator token.

+ +

E4X

+ +

下面介绍一下为E4X提供支持的节点类型.

+ +
注: E4X不是ECMAScript规范(ECMA-262)的一部分,它是一个单独的标准(ECMA-357).
+ +

声明

+ +
interface XMLDefaultDeclaration <: Declaration {
+    type: "XMLDefaultDeclaration";
+    namespace: Expression;
+}
+
+ +

一个默认xml命名空间声明

+ +

表达式

+ +
interface XMLAnyName <: Expression {
+    type: "XMLAnyName";
+}
+
+ +

The special E4X wildcard pseudo-identifier *.

+ +
interface XMLQualifiedIdentifier <: Expression {
+    type: "XMLQualifiedIdentifier";
+    left: Identifier | XMLAnyName;
+    right: Identifier | Expression;
+    computed: boolean;
+}
+
+ +

An E4X qualified identifier, i.e., a pseudo-identifier using the namespace separator ::. If the qualified identifier has a computed name (i.e., the id::[expr] form), then computed is true and the right property is an expression.

+ +
interface XMLFunctionQualifiedIdentifier <: Expression {
+    type: "XMLFunctionQualifiedIdentifier";
+    right: Identifier | Expression;
+    computed: boolean;
+}
+
+ +

An E4X identifier qualified by the function keyword, e.g. function::id.

+ +
注: function-qualified identifiers 是SpiderMonkey特有的.
+ +
interface XMLAttributeSelector <: Expression {
+    type: "XMLAttributeSelector";
+    attribute: Expression;
+}
+
+ +

An E4X attribute selector expression, i.e., an @ expression.

+ +
interface XMLFilterExpression <: Expression {
+    type: "XMLFilterExpression";
+    left: Expression;
+    right: Expression;
+}
+
+ +

An E4X list filter expression, i.e., an expression of the form expr.(expr).

+ +
interface XMLElement <: XML, Expression {
+    type: "XMLElement";
+    contents: [ XML ];
+}
+
+ +

An E4X literal representing a single XML element.

+ +
interface XMLList <: XML, Expression {
+    type: "XMLList";
+    contents: [ XML ];
+}
+
+ +

An E4X literal representing a list of XML elements.

+ +

XML

+ +
interface XML <: Node { }
+
+ +

XML data.

+ +
interface XMLEscape <: XML {
+    type "XMLEscape";
+    expression: Expression;
+}
+
+ +

XML data with an escaped JavaScript expression.

+ +
interface XMLText <: XML {
+    type: "XMLText";
+    text: string;
+}
+
+ +

Literal XML text.

+ +
interface XMLStartTag <: XML {
+    type: "XMLStartTag";
+    contents: [ XML ];
+}
+
+ +

An XML start tag.

+ +
interface XMLEndTag <: XML {
+    type: "XMLEndTag";
+    contents: [ XML ];
+}
+
+ +

An XML end tag.

+ +
interface XMLPointTag <: XML {
+    type: "XMLPointTag";
+    contents: [ XML ];
+}
+
+ +

An XML point tag.

+ +
interface XMLName <: XML {
+    type: "XMLName";
+    contents: string | [ XML ];
+}
+
+ +

An XML name.

+ +
interface XMLAttribute <: XML {
+    type: "XMLAttribute";
+    value: string;
+}
+
+ +

An XML attribute value.

+ +
interface XMLCdata <: XML {
+    type: "XMLCdata";
+    contents: string;
+}
+
+ +

An XML CDATA node.

+ +
interface XMLComment <: XML {
+    type: "XMLComment";
+    contents: string;
+}
+
+ +

An XML comment.

+ +
interface XMLProcessingInstruction <: XML {
+    type: "XMLProcessingInstruction";
+    target: string;
+    contents: string | null;
+}
+
+ +

An XML processing instruction.

+ +

Builder objects

+ +

The optional builder parameter to Reflect.parse() makes it possible to construct user-specified data from the parser, rather than the default Node objects. Builder objects may contain any of the callback methods described in this section.

+ +

Each callback can produce any custom, user-defined datatype; these are referred to below as CustomExpression, CustomStatement, etc.

+ +
注: Because this library uses null for optional nodes, it is recommended that user-defined datatypes not use null as a representation of an AST node.
+ +

If the loc option is enabled (see the Reflect.parse() options above), then each callback is provided with the source location information of the parsed node as an extra parameter.

+ +

All builder callbacks are optional. When a callback is missing, the default format is used, but the provided builder methods are still used recursively for sub-nodes.

+ +

Programs

+ +
program(body[, loc])
+ +
body: [ CustomStatement ]
+loc: SourceLocation
+
+ +

返回: CustomProgram

+ +

Callback to produce a custom program node.

+ +

Statements

+ +
emptyStatement([loc])
+ +
loc: SourceLocation
+
+ +

返回: CustomStatement

+ +

Callback to produce a custom empty statement node.

+ +
blockStatement(body[, loc])
+ +
body: CustomStatement
+loc: SourceLocation
+
+ +

返回: CustomStatement

+ +

Callback to produce a custom block statement node.

+ +
expressionStatement(expr[, loc])
+ +
expr: CustomExpression
+loc: SourceLocation
+
+ +

返回: CustomStatement

+ +

Callback to produce a custom expression statement node.

+ +
labeledStatement(label, body[, loc])
+ +
label: CustomIdentifier
+body: CustomStatement
+loc: SourceLocation
+
+ +

返回: CustomStatement

+ +

Callback to produce a custom labeled statement node.

+ +
ifStatement(test, cons, alt[, loc])
+ +
test: CustomExpression
+cons: CustomStatement
+alt: CustomStatement | null
+loc: SourceLocation
+
+ +

返回: CustomStatement

+ +

Callback to produce a custom if statement node.

+ +
switchStatement(disc, cases, isLexical[, loc])
+ +
disc: CustomExpression
+cases: [ CustomSwitchCase ]
+isLexical: boolean
+loc: SourceLocation
+
+ +

返回: CustomStatement

+ +

Callback to produce a custom switch statement node. The isLexical flag is metadata indicating whether the switch statement contains any unnested let declarations (and therefore introduces a new lexical scope).

+ +
whileStatement(test, body[, loc])
+ +
test: CustomExpression
+body: CustomStatement
+loc: SourceLocation
+
+ +

返回: CustomStatement

+ +

Callback to produce a custom while statement node.

+ +
doWhileStatement(body, test[, loc])
+ +
body: CustomStatement
+test: CustomExpression
+loc: SourceLocation
+
+ +

返回: CustomStatement

+ +

Callback to produce a custom do-while statement node.

+ +
forStatement(init, test, update, body[, loc])
+ +
init: CustomVariableDeclaration | CustomExpression | null
+test: CustomExpression | null
+update: CustomExpression | null
+body: CustomStatement
+loc: SourceLocation
+
+ +

返回: CustomStatement

+ +

Callback to produce a custom for statement node.

+ +
forInStatement(left, right, body, isForEach[, loc])
+ +
left: CustomVariableDeclaration | CustomExpression
+right: CustomExpression
+body: CustomStatement
+isForEach: boolean
+loc: SourceLocation
+
+ +

返回: CustomStatement

+ +

Callback to produce a custom for-in statement node. The isForEach flag indicates whether the node is a for each statement.

+ +
breakStatement(label[, loc])
+ +
label: CustomIdentifier | null
+loc: SourceLocation
+
+ +

返回: CustomStatement

+ +

Callback to produce a custom break statement node.

+ +
continueStatement(label[, loc])
+ +
label: CustomIdentifier | null
+loc: SourceLocation
+
+ +

返回: CustomStatement

+ +

Callback to produce a custom continue statement node.

+ +
withStatement(obj, body[, loc])
+ +
obj: CustomExpression
+body: CustomStatement
+loc: SourceLocation
+
+ +

返回: CustomStatement

+ +

Callback to produce a custom with statement node.

+ +
returnStatement(arg[, loc])
+ +
arg: CustomExpression | null
+loc: SourceLocation
+
+ +

返回: CustomStatement

+ +

Callback to produce a custom return statement node.

+ +
tryStatement(body, handlers, fin[, loc])
+ +
body: CustomStatement
+handlers: [ CustomCatchClause ]
+fin: CustomStatement | null
+loc: SourceLocation
+
+ +

返回: CustomStatement

+ +

Callback to produce a custom try statement node.

+ +
throwStatement(arg[, loc])
+ +
arg: CustomExpression
+loc: SourceLocation
+
+ +

返回: CustomStatement

+ +

Callback to produce a custom throw statement node.

+ +
debuggerStatement([loc])
+ +
loc: SourceLocation
+
+ +

返回: CustomStatement

+ +

Callback to produce a custom debugger statement node.

+ +
letStatement(head, body[, loc])
+ +
head: [ CustomDeclarator ]
+body: CustomStatement
+loc: SourceLocation
+
+ +

返回: CustomStatement

+ +

Callback to produce a custom let statement node.

+ +

声明

+ +
functionDeclaration(name, args, body, isGenerator, isExpression[, loc])
+ +
name: string
+args: [ CustomPattern ]
+body: CustomStatement | CustomExpression
+isGenerator: boolean
+isExpression: boolean
+loc: SourceLocation
+
+ +

返回: CustomDeclaration

+ +

Callback to produce a custom function declaration node.

+ +
variableDeclaration(kind, dtors[, loc])
+ +
kind: "const" | "let" | "var"
+dtors: [ CustomDeclarator ]
+loc: SourceLocation
+
+ +

返回: CustomDeclaration

+ +

Callback to produce a custom variable declaration node.

+ +
variableDeclarator(patt, init[, loc])
+ +
patt: CustomPattern
+init: CustomExpression | null
+loc: SourceLocation
+
+ +

返回: CustomDeclarator

+ +

Callback to produce a custom variable declarator node.

+ +

表达式

+ +
sequenceExpression(exprs[, loc])
+ +
exprs: [ CustomExpression ]
+loc: SourceLocation
+
+ +

返回: CustomExpression

+ +

Callback to produce a custom sequence expression node.

+ +
conditionalExpression(test, cons, alt[, loc])
+ +
test: CustomExpression
+cons: CustomExpression
+alt: CustomExpression
+loc: SourceLocation
+
+ +

返回: CustomExpression

+ +

Callback to produce a custom conditional expression node.

+ +
unaryExpression(op, arg, isPrefix[, loc])
+ +
op: UnaryOperator
+arg: CustomExpression
+isPrefix: boolean
+loc: SourceLocation
+
+ +

返回: CustomExpression

+ +

Callback to produce a custom unary expression node.

+ +
binaryExpression(op, left, right[, loc])
+ +
op: BinaryOperator
+left: CustomExpression
+right: CustomExpression
+loc: SourceLocation
+
+ +

返回: CustomExpression

+ +

Callback to produce a custom binary expression node.

+ +
assignmentExpression(op, left, right[, loc])
+ +
op: AssignmentOperator
+left: CustomExpression
+right: CustomExpression
+loc: SourceLocation
+
+ +

返回: CustomExpression

+ +

Callback to produce a custom assignment expression node.

+ +
logicalExpression(op, left, right[, loc])
+ +
op: LogicalOperator
+left: CustomExpression
+right: CustomExpression
+loc: SourceLocation
+
+ +

返回: CustomExpression

+ +

Callback to produce a custom logical expression node.

+ +
updateExpression(op, arg, isPrefix[, loc])
+ +
op: UpdateOperator
+arg: CustomExpression
+isPrefix: boolean
+loc: SourceLocation
+
+ +

返回: CustomExpression

+ +

Callback to produce a custom update expression node.

+ +
newExpression(callee, args[, loc])
+ +
callee: CustomExpression
+args: [ CustomExpression ]
+loc: SourceLocation
+
+ +

返回: CustomExpression

+ +

Callback to produce a custom new-expression node.

+ +
callExpression(callee, args[, loc])
+ +
callee: CustomExpression
+args: [ CustomExpression ]
+loc: SourceLocation
+
+ +

返回: CustomExpression

+ +

Callback to produce a custom function call node.

+ +
memberExpression(obj, prop, isComputed[, loc])
+ +
obj: CustomExpression
+prop: CustomIdentifier | CustomExpression
+isComputed: boolean
+loc: SourceLocation
+
+ +

返回: CustomExpression

+ +

Callback to produce a custom member expression node.

+ +
functionExpression(name, args, body, isGenerator, isExpression[, loc])
+ +
name: CustomIdentifier | null
+args: [ CustomPattern ]
+body: CustomStatement | CustomExpression
+isGenerator: boolean
+isExpression: boolean
+loc: SourceLocation
+
+ +

返回: CustomExpression

+ +

Callback to produce a custom function expression node.

+ +
arrayExpression(elts[, loc])
+ +
elts: [ CustomExpression | null ]
+loc: SourceLocation
+
+ +

返回: CustomExpression

+ +

Callback to produce a custom array expression node.

+ +
objectExpression(props[, loc])
+ +
props: [ CustomObjectProperty ]
+loc: SourceLocation
+
+ +

返回: CustomExpression

+ +

Callback to produce a custom object expression node.

+ +
thisExpression([loc])
+ +
loc: SourceLocation
+
+ +

返回: CustomExpression

+ +

Callback to produce a custom this expression node.

+ +
graphExpression(index, expr[, loc])
+ +
index: uint32 >= 1
+expr: CustomExpression
+loc: SourceLocation
+
+ +

返回: CustomExpression

+ +

Callback to produce a custom graph expression node.

+ +
graphIndexExpression(index[, loc])
+ +
index: uint32 >= 1
+loc: SourceLocation
+
+ +

返回: CustomExpression

+ +

Callback to produce a custom graph index expression node.

+ +
comprehensionExpression(body, blocks, filter[, loc])
+ +
body: CustomExpression
+blocks: [ CustomComprehensionBlock ]
+filter: CustomExpression | null
+loc: SourceLocation
+
+ +

返回: CustomExpression

+ +

Callback to produce a custom comprehension expression node.

+ +
generatorExpression(body, blocks, filter[, loc])
+ +
body: CustomExpression
+blocks: [ CustomComprehensionBlock ]
+filter: CustomExpression | null
+loc: SourceLocation
+
+ +

返回: CustomExpression

+ +

Callback to produce a custom generator expression node.

+ +
yieldExpression(arg[, loc])
+ +
arg: CustomExpression
+loc: SourceLocation
+
+ +

返回: CustomExpression

+ +

Callback to produce a custom yield expression node.

+ +
letExpression(head, body[, loc])
+ +
head: [ CustomDeclarator ]
+body: CustomExpression
+loc: SourceLocation
+
+ +

返回: CustomExpression

+ +

Callback to produce a custom let expression node.

+ +

Patterns

+ +
arrayPattern(elts[, loc])
+ +
elts: [ CustomPattern | null ]
+loc: SourceLocation
+
+ +

返回: CustomPattern

+ +

Callback to produce a custom array destructuring pattern node.

+ +
objectPattern(props[, loc])
+ +
props: [ CustomPropertyPattern ]
+loc: SourceLocation
+
+ +

返回: CustomPattern

+ +

Callback to produce a custom object destructuring pattern node.

+ +
propertyPattern(key, patt[, loc])
+ +
key: CustomLiteral | CustomIdentifier
+patt: CustomPattern
+loc: SourceLocation
+
+ +

返回: CustomPropertyPattern

+ +

Callback to produce a custom object property destructuring pattern node.

+ +

Clauses

+ +
switchCase(test, cons[, loc])
+ +
test: CustomExpression | null
+cons: [ CustomStatement ]
+loc: SourceLocation
+
+ +

返回: CustomSwitchCase

+ +

Callback to produce a custom case or default clause node. The test argument is null if and only if the node is a default clause.

+ +
catchClause(arg, guard, body[, loc])
+ +
arg: CustomPattern
+guard: CustomExpression
+body: CustomStatement
+loc: SourceLocation
+
+ +

返回: CustomCatchClause

+ +

Callback to produce a custom catch clause node.

+ +
comprehensionBlock(left, right, isForEach[, loc])
+ +
left: CustomPattern
+right: CustomExpression
+isForEach: boolean
+loc: SourceLocation
+
+ +

返回: CustomComprehensionBlock

+ +

Callback to produce a custom comprehension block node. The isForEach flag indicates whether the node is a for each block.

+ +

Miscellaneous

+ +
identifier(name[, loc])
+ +
name: string
+loc: SourceLocation
+
+ +

返回: CustomIdentifier/CustomPattern/CustomExpression

+ +

Callback to produce a custom identifier node.

+ +
literal(val[, loc])
+ +
val: string | boolean | null | number | RegExp
+loc: SourceLocation
+
+ +

返回: CustomLiteral / CustomExpression

+ +

Callback to produce a custom literal node.

+ +
property(kind, key, val[, loc])
+ +
kind: "init" | "get" | "set"
+key: CustomLiteral | CustomIdentifier
+val: CustomExpression
+loc: SourceLocation
+
+ +

返回: CustomObjectProperty

+ +

Callback to produce a custom object property initializer node.

+ +

E4X

+ +

Declarations

+ +
xmlDefaultDeclaration(ns[, loc])
+ +
loc: SourceLocation
+
+ +

返回: CustomDeclaration

+ +

Callback to produce a custom XML default namespace declaration node.

+ +

Expressions

+ +
xmlAnyName([loc])
+ +
loc: SourceLocation
+
+ +

返回: CustomXMLAnyName/CustomXML/CustomExpression

+ +

Callback to produce a custom XML node for the wildcard pseudo-identifier *.

+ +
xmlAttributeSelector(expr[, loc])
+ +
expr: CustomExpression
+loc: SourceLocation
+
+ +

返回: CustomXML/CustomExpression

+ +

Callback to produce a custom XML attribute selector node.

+ +
xmlFilterExpression(left, right[, loc])
+ +
left: CustomExpression
+right: CustomExpression
+loc: SourceLocation
+
+ +

返回: CustomXML/CustomExpression

+ +

Callback to produce a custom XML filter expression node.

+ +
xmlQualifiedIdentifier(left, right, isComputed[, loc])
+ +
left: CustomIdentifier | CustomXMLAnyName
+right: CustomIdentifier | CustomExpression
+isComputed: boolean
+loc: SourceLocation
+
+ +

返回: CustomXML/CustomExpression

+ +

Callback to produce a custom qualified identifier node.

+ +
xmlFunctionQualifiedIdentifier(right, isComputed[, loc])
+ +
right: CustomIdentifier | CustomExpression
+isComputed: boolean
+loc: SourceLocation
+
+ +

返回: CustomXML/CustomExpression

+ +

Callback to produce a custom XML function-qualified identifier node.

+ +
xmlElement(contents[, loc])
+ +
contents: [ CustomXML ]
+loc: SourceLocation
+
+ +

返回: CustomXML / CustomExpression

+ +

Callback to produce a custom XML element node.

+ +
xmlList(contents[, loc])
+ +
contents: [ CustomXML ]
+loc: SourceLocation
+
+ +

返回: CustomXML/CustomExpression

+ +

Callback to produce a custom XML list node.

+ +

XML

+ +
xmlEscape(expr[, loc])
+ +
expr: CustomExpression
+loc: SourceLocation
+
+ +

返回: CustomXML

+ +

Callback to produce a custom XML escape node.

+ +
xmlText(text[, loc])
+ +
text: string
+loc: SourceLocation
+
+ +

返回: CustomXML

+ +

Callback to produce a custom XML text node.

+ +
xmlStartTag(contents[, loc])
+ +
contents: [ CustomXML ]
+loc: SourceLocation
+
+ +

返回: CustomXML

+ +

Callback to produce a custom XML start-tag node.

+ +
xmlEndTag(contents[, loc])
+ +
contents: [ CustomXML ]
+loc: SourceLocation
+
+ +

返回: CustomXML

+ +

Callback to produce a custom XML end-tag node.

+ +
xmlPointTag(contents[, loc])
+ +
contents: [ CustomXML ]
+loc: SourceLocation
+
+ +

返回: CustomXML

+ +

Callback to produce a custom XML point tag node.

+ +
xmlName(contents[, loc])
+ +
contents: string | [ CustomXML ]
+loc: SourceLocation
+
+ +

返回: CustomXML

+ +

Callback to produce a custom XML name node.

+ +
xmlAttribute(value[, loc])
+ +
value: string
+loc: SourceLocation
+
+ +

返回: CustomXML

+ +

Callback to produce a custom XML attribute node.

+ +
xmlCdata(contents[, loc])
+ +
contents: string
+loc: SourceLocation
+
+ +

返回: CustomXML

+ +

Callback to produce a custom XML CDATA node.

+ +
xmlComment(contents[, loc])
+ +
contents: string
+loc: SourceLocation
+
+ +

返回: CustomXML

+ +

Callback to produce a custom XML comment node.

+ +
xmlProcessingInstruction(target, contents[, loc])
+ +
target: string
+contents: string | null
+loc: SourceLocation
+
+ +

返回: CustomXML

+ +

Callback to produce a custom XML processing instruction node.

diff --git a/files/zh-cn/mozilla/projects/spidermonkey/releases/index.html b/files/zh-cn/mozilla/projects/spidermonkey/releases/index.html new file mode 100644 index 0000000000..fd88b37529 --- /dev/null +++ b/files/zh-cn/mozilla/projects/spidermonkey/releases/index.html @@ -0,0 +1,42 @@ +--- +title: SpiderMonkey releases +slug: Mozilla/Projects/SpiderMonkey/Releases +translation_of: Mozilla/Projects/SpiderMonkey/Releases +--- +
{{SpiderMonkeySidebar("Releases")}}
+ +
+

本页开列了 SpiderMonkey 的版本记录.

+
+ +
+

注意: 独立的 SpiderMonkey 并不是官方产品. Our continuous integration system does produce a tarball that is built into a binary that runs our smoke tests, but we do not maintain it nor actively test its suitability for general embedding. We have periodically created "releases", but they are best-effort and incomplete. We do happily accept patches, and make some effort to keep the tip of the Gecko tree minimally working as an embeddable source package. We are very limited in our ability to support older versions, including those labeled as "releases" on this page.

+
+ +

The easiest way to fetch the version corresponding to the current Firefox release is to visit the treeherder page for the release repository and click on the first SM(pkg) link you see. That will open a small window in the bottom left with a line like " mozjs-57.0.1.tar.bz2".

+ +

当前版本

+ + + +

Future release

+ + + +

过往版本

+ + diff --git a/files/zh-cn/mozilla/projects/spidermonkey/split_object/index.html b/files/zh-cn/mozilla/projects/spidermonkey/split_object/index.html new file mode 100644 index 0000000000..86d82e7d58 --- /dev/null +++ b/files/zh-cn/mozilla/projects/spidermonkey/split_object/index.html @@ -0,0 +1,72 @@ +--- +title: Split object +slug: Mozilla/Projects/SpiderMonkey/Split_object +translation_of: Mozilla/Projects/SpiderMonkey/Split_object +--- +

In SpiderMonkey, a split object is made up of two JSObjects: an inner object and an outer object.

+ +

Each half of a split object always has a pointer to the other half. Inner objects implement the JSExtendedClass.outerObject hook, which returns a pointer to the corresponding outer object. Outer objects implement the JSExtendedClass.innerObject hook. But the association is not fixed. An outer object may be associated with different inner objects at different times.

+ +

This feature is complicated. Programs other than Mozilla that embed SpiderMonkey should avoid using split objects.

+ +

The window object

+ +

Split objects were introduced to resolve a problem posed by the window object. Three interrelated requirements on the window object seemed to conflict.

+ + + + + + + +

Split objects were the solution. The inner window object is different for each page a browser window visits. It serves as the "globals" object and provides the JSPrincipals for scripts on that page. Access to inner window properties is fast. The outer window object is the object returned by window.open. It represents the window or tab itself and survives as the user navigates in that window or tab. The window object's JSClass.resolve hook ensures that properties of the inner object are visible via the outer object, if the running code has the right principals to access them. This privilege check may be slow.

+ +

See {{ interwiki('wikimo', 'Gecko:SplitWindow', 'wikimo:Gecko:SplitWindow') }} and {{ Bug(296639) }} for more discussion.

+ +

See also http://groups.google.com/group/mozil...81825b338fb84f

+ +

Details

+ +

This section describes split objects as a feature of the JSAPI. It catalogues (and tries to explain) the subtle ways in which split objects affect SpiderMonkey's behavior.

+ +

Split objects are only useful for implementing objects that will be on the scope chain of functions. SpiderMonkey assumes that inner and outer objects are dangerous in two different and complementary ways.

+ +

Inner objects are dangerous because they have fast property accessors that do not perform security checks. Therefore, no function may be allowed to see an inner object that has different JSPrincipals. Apart from the security issue, if one page directly or indirectly gets a reference to another page's window object, that window object must appear to behave like the outer window and navigate from page to page. SpiderMonkey arranges this by not allowing JS code to see inner objects at all. To enforce this rule:

+ + + +

Outer objects are dangerous because their JSPrincipals may change over time. Because a Function inherits the JSPrincipals of its lexical scope (specifically, the nearest principals-aware object in its scope chain), untrusted code must never be able to make an outer object appear in a Function's scope chain. Again, SpiderMonkey enforces a slightly stronger rule: outer objects may never appear in a scope chain at all, except when put there by an explicit C-level JSAPI call (to JS_SetParent or equivalent). (Several objects, such as window.location and window.navigator, are intentionally parented to the outer window object using such APIs.) To enforce this rule:

+ + + + + +

Inner and outer objects are in certain other respects the same object:

+ + + +

Note that none of the rules listed here affects ordinary property accesses. SpiderMonkey's split object support, by itself, does not cause inner object properties to appear on the outer object or vice versa. Split objects that need this behavior must implement it in custom JSClass hooks. In the case of window, each half has custom hooks.

-- cgit v1.2.3-54-g00ecf