【问题标题】:document.getElementsByTagName('ul')[0]["__proto__"] instanceof HTMLUListElement is falsedocument.getElementsByTagName('ul')[0]["__proto__"] instanceof HTMLUListElement 为 false
【发布时间】:2020-11-29 08:08:40
【问题描述】:

我的网站中有原生和 Web 组件。我使用文档注册元素 polyfill。当我检查 document.getElementsByTagName('ul')[0]["__proto__"] instanceof HTMLUListElement 时返回 false。

当我检查 HTMLUListElement 是控制台日志时,它返回

ƒ (e){var t,n;return(e=e||this)[Q]||(ae=!0,t=ie[le.get(e.constructor)],(e=(n=te&&1===t.create.length)?Reflect.construct(r,Y,t.constructor):d.createElement.apply(d,t.create))[Q]=!0,ae=!1,n||tt(e)),e}

当我在控制台日志中检查document.getElementsByTagName('ul')[0]['__proto__'] 时。它返回

HTMLUListElement {Symbol(Symbol.toStringTag): "HTMLUListElement", constructor: 

如果我得到 HTMLUListElement 和我的 DOM 节点构造函数不同的答案,它将帮助我解决问题。任何帮助表示赞赏。

这仅在我第一次以 chrome 隐身模式加载页面时发生。我无法在其他浏览器中进行测试。

提前致谢。

【问题讨论】:

  • (new Array()).constructor instanceof Array 也是错误的。构造函数是一个函数,所以我不知道你期望什么。
  • 构造函数将是一个函数,而不是元素类型。
  • @NiettheDarkAbsol 我的意思是 document.getElementsByTagName('ul')[0]['_proto_']。它应该返回它为 HTMLUListElement 返回的内容。
  • 我收到了function HTMLUListElement() { [native code] },不是一些缩小的东西,这与您的注册元素 polyfill 有关吗?

标签: javascript web-component polyfills babel-polyfill incognito-mode


【解决方案1】:

这是正常的。

Object.getPrototypeOf(document.createElement("ul")) === HTMLUListElement.prototype

这意味着

document.createElement("ul") instanceof HTMLUListElement

将评估为true,但是

Object.getPrototypeOf(document.createElement("ul")) instanceof HTMLUListElement
// i.e.
HTMLUListElement.prototype instanceof HTMLUListElement

将是false,因为该对象不会从自身继承。

【讨论】:

  • 感谢您的回答。您的逻辑适用于使用 document.createElement 创建的新元素。但是对于已经渲染的元素,它会失败。
  • document.getElementsByTagName('ul')[0] 应该与document.createElement("ul") 完全相同(当然,除非是undefined)。您可以尝试不加载该 polyfil 吗?它似乎与内置函数混淆。
猜你喜欢
  • 1970-01-01
  • 2016-02-09
  • 2014-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-22
相关资源
最近更新 更多