浏览v8在 src
目录下,有一些 js 文件,提供了一些基本的 JS 对象,如 Math、Array 等。浏览这些文件,我看到名称中包含百分号(%)的标识符,即%Foo
。我一开始天真地认为这是 JS 标识符中其他允许的字符,但是当我在 shell 中尝试它时,它对我大喊大叫,说我违反了语法规则。但如果是语法错误,那么 d8 是如何工作的呢?以下是实际源代码的示例:
src/apinatives.js 第 44 至 47 行,从 github/v8/v8 进行 git 克隆
function Instantiate(data, name) {
if (!%IsTemplate(data)) return data;
var tag = %GetTemplateField(data, kApiTagOffset);
switch (tag) {
src/apinatives.js 第 41 到 43 行,从 github/v8/v8 进行 git 克隆
function SetConstructor() {
if (%_IsConstructCall()) {
%SetInitialize(this);
为什么这个标识符不会产生语法错误。所有 js 文件,包括 math.js 和 string.js 以及所有其他文件?:wq
最佳答案
这在技术上不是有效的 JavaScript。这些是对 V8 runtime functions 的调用。从该页面:
Much of the JavaScript library is implemented in JavaScript code itself, using a minimal set of C++ runtime functions callable from JavaScript. Some of these are called using names that start with %, and using the flag "--allow-natives-syntax". Others are only called by code generated by the code generators, and are not visible in JS, even using the % syntax.
如果你查看parser.cc
您可以看到一些与 allow_natives_syntax
相关的代码,这些代码确定解析器是否接受 V8 用于与其运行时交互的 JavaScript 语言的此扩展。必须在启用该选项的情况下解析这些文件。
我推测 V8 默认情况下不允许您进行这些调用,因为这与 JavaScript 标准相矛盾,而且它可能允许您对运行时执行您不应该执行的操作。
关于javascript - % 符号如何用在标识符中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40716305/