javascript - 对字符串的 promise - [object Object] 或 [object Promise]?

标签 javascript google-chrome firefox promise ecmascript-6

我在 FF 和 Chrome 中执行这段代码。

Object.prototype.toString.call(Promise.resolve())

结果:

  • Firefox Nightly 44 - [object Promise]
  • Chrome Canary 48(带有标志)- [object Promise]
  • Chrome 46 - [对象对象]

EcmaScript specification25.4.4.5 Promise.resolve(x) 章中引用:

The resolve function returns either a new promise resolved with the passed argument, or the argument itself if the argument is a promise produced by this constructor.

  1. 设 C 为 this 值。
  2. 如果 Type(C) 不是 Object,则抛出 TypeError 异常。
  3. 如果 IsPromise(x) 为真,
    • 设 xConstructor 为 Get(x, "constructor")。
    • ReturnIfAbrupt(xConstructor)。
    • 如果 SameValue(xConstructor, C) 为真,则返回 x。
  4. 设 promiseCapability 为 NewPromiseCapability(C)。
  5. ReturnIfAbrupt(promiseCapability)。
  6. 设 resolveResult 为 Call(promiseCapability.[[Resolve]], undefined, «x»)。
  7. ReturnIfAbrupt(resolveResult)。
  8. 返回 promiseCapability.[[Promise]]。

所以 promiseCapability.[[Promise]] toString 是浏览器中的结果。

PromiseCapability 记录包含 Table 57 中列出的字段:

-------------------------------------------------------------------
| Field Name  | Value     | Meaning                               |
-------------------------------------------------------------------
| [[Promise]] | An object | An object that is usable as a promise |
-------------------------------------------------------------------

所以[[Promise]]是一个对象,必须是[object Object]

最佳答案

是啊!欢迎来到 ES2015 :)

这是 Symbol 的特征在浏览器中的实现。 符号 affect Object.prototype.toString.call 通过Symbol.toStringTag:

  • tagGet (O, @@toStringTag)
  • ReturnIfAbrupt(标签)
  • 如果 Type(tag) 不是 String,则让 tag 为 builtinTag
  • 返回 String,它是连接 [object "、tag 和 "]" 的结果。

所以Symbol做一个对象的默认字符串描述obj:

'[object '+obj[Symbol.toStringTag]+']'

从这个 article 获取更多关于 ES2015 aka ES6 Symbol 的信息.

关于javascript - 对字符串的 promise - [object Object] 或 [object Promise]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33439487/

相关文章:

javascript - chrome.fileSystem api 文件到临时目录

javascript - Chrome 无法进行 jquery 表单验证

JavaScript、图像和 css 不会通过 HTTPS 在 Firefox 中加载

html - 在不降低 Firefox 滚动速度的情况下摆脱 CSS 字体大小填充

html - CSS 转换在 Firefox 中不起作用

javascript - 如何通配符匹配 querySelectorAll 中的类名?

javascript - 执行多个ajax请求后调用函数

当我的 div 包含所有 5 张图像时,Javascript 更改按钮文本

javascript - 为什么 jQuery 悬停效果不起作用?

javascript - Chrome - 调试 WebGL 崩溃 ("Rats! WebGL hit a snag.")