如何阅读“原生代码”JavaScript 函数?

有什么方法可以看到 JavaScript 本机代码的声明吗?每当我试图在 Chrome 或 Firefox 中查看一个本地函数时,它都会显示“ native code”:

> String.fromCharCode
function fromCharCode() { [native code] }

这是什么意思,有没有什么工具可以帮助我阅读实际的代码?

62815 次浏览

Not within the JavaScript environment, but you can view the source for the open-source implementations.

Google V8: http://code.google.com/p/v8/source/browse

Mozilla SpiderMonkey: https://developer.mozilla.org/en/SpiderMonkey

The reason Chrome or Firefox says that the code is native is that it really is native - the WebKit and Firefox developers have coded up that functionality in C or C++, not JavaScript. However, if you want to see the actual code, you can look at the source repositories for Chromium and Firefox.

Firefox now supports the inspection of "[native code]" objects via standard dev tools.

To see it in action:

  1. update Firefox (definitely works w/ v68+, may work with older versions as well)
  2. open dev tools
  3. go to the Console
  4. type the name of a native object, e.g., "Document"
  5. hit return
  6. go nuts on all those little dropdown arrows

FireFox - inspect "native code" - Document object

Chrome still returns ƒ Document() { [native code] }, unfortunately.

Chrome - DON'T inspect "native code" - disappointment

Chromium Code Search provides a good way to read javascript native code. This post addresses a litter bit about how to use it. And in this video, you can see an example.