为什么将其他对象分配给内置对象(例如文档、窗口)没有意义

Why it doesn't make sense to assign other object to builtin objects, such as document, window?

本文关键字:对象 文档 窗口 有意义 其他 分配 为什么 内置      更新时间:2023-09-26
<script>
this.document = "xxxx";  // why it doesn't make sense?
console.log(document);   // still show document obj in devtools
</script>

我想也许这会被javascript引擎禁止。

window.document不是

可写属性。如果你想要一个名为document的局部变量,你可以这样做:

(function(){
  var document = 'xxxx';
  console.log(document);
})();

和:

new function(){
  this.document = 'xxxx';
  console.log(this.document);
};

两者都将记录"xxxx">

有时这是有意义的 - 并且是允许的,例如您可以重新分配内负函数window.alert

但在99%的情况下,你最好不要管它。

重新分配内置 ins 会产生不可移植的行为。

Library A 严重依赖 document.getElementById。 库 B 依赖于自己的自定义版本,但将文档原型上的 getElementById 替换为自己的自定义版本。 库 A 中断。

因此,库 A(旨在与所有浏览器配合使用并针对所有浏览器进行测试(将不起作用。

这与全局变量的参数相同。 内置基本上是全局变量。