JavaScript 只是一种语言,其实现之一是 V8
引擎。它在 chrome 和 node.js 中都有使用。
DOM
支持不是 JavaScript 语言特性,它是浏览器特性(纯 JS 中没有 DOM
)。同样,XMLHttpRequest
不是 JavaScript 的一部分。它是 JS 语言的浏览器插件。
我的问题与Philip Roberts' JS conf EU有关谈谈他所说的,除其他外,setTimeout
不在 V8 中。我认为他可能是错的,但我不确定,这是我的问题。
当我打开 node.js(基于 V8)控制台并键入以下内容时:
> Promise
[Function: Promise]
> setTimeout
[Function]
> setInterval
[Function]
> XMLHttpRequest
ReferenceError: XMLHttpRequest is not defined
at repl:1:1
at REPLServer.defaultEval (repl.js:262:27)
at bound (domain.js:287:14)
at REPLServer.runBound [as eval] (domain.js:300:12)
at REPLServer.<anonymous> (repl.js:431:12)
at emitOne (events.js:82:20)
at REPLServer.emit (events.js:169:7)
at REPLServer.Interface._onLine (readline.js:211:10)
at REPLServer.Interface._line (readline.js:550:8)
at REPLServer.Interface._ttyWrite (readline.js:827:14)
我看到了:
Promise
原型(prototype)在那里,因为它是 ES6 的一部分,已经在新版本的 Node 下可用。它是JS作为一种语言 的一部分
XMLHttpRequest
不存在,因为它只在浏览器中可用,它不是语言的一部分setTimeout
和setInterval
都在那里。 Philip Roberts 说它们不是 - 但我看到它们在 node.js 下可用并且 我认为它们应该是,因为setTimeout
/setInterval
在单线程中有意义/异步环境,无论是浏览器还是服务器。
我猜他知道他在说什么,但我想明白为什么:)
编辑:
我看到 setTimeout
是 window
对象上的一个函数。基本上,window
是非标准的东西。
最佳答案
他是对的,因为它们不是 V8 的一部分。然而,它们是,part of node.js (通过默认包含的模块),并以与浏览器规范兼容的方式设计:
The timer module exposes a global API for scheduling functions to be called at some future period of time. Because the timer functions are globals, there is no need to call require('timers') to use the API.
The timer functions within Node.js implement a similar API as the timers API provided by Web Browsers but use a different internal implementation that is built around the Node.js Event Loop.
关于JavaScript:浏览器支持 vs 纯语言支持:setTimeout、setInterval,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38529515/