JavaScript:浏览器支持与纯语言支持:setTimeout、setInterval

JavaScript: browsers support vs pure language support: setTimeout, setInterval

JavaScript 只是一种语言,其实现之一是 V8 引擎。它用于 chrome 以及 node.js.

DOM 支持不是 JavaScript 语言特性,它是浏览器特性(纯 JS 中没有 DOM)。同样,XMLHttpRequest 不是 JavaScript 的一部分。它是 JS 语言的浏览器插件。

我的问题Philip Roberts' JS conf EU谈话有关,他说,除其他外,setTimeout不在V8[=54中=].我认为他可能是错的,但我不确定,这是我的问题。

当我打开 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 原型在那里,因为它是 ES6 的一部分,已经在新版本的节点下可用。它是 JS 语言的一部分
  • XMLHttpRequest 不存在,因为它只在浏览器中可用,它不是语言的一部分
  • setTimeoutsetInterval都有。 Philip Roberts 说它们不是 - 但我看到它们在 node.js 和 下可用我认为它们应该是,因为 setTimeout/setInterval 在 single-threaded/async 中有意义环境,无论是浏览器还是服务器.

我猜他知道他在说什么,但我想明白为什么:)


编辑:

我看到 setTimeoutwindow 对象上的函数。基本上,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.