【发布时间】:2021-02-21 05:00:13
【问题描述】:
在向 HTML 中写东西时,我们通常使用:document.write();(“D”是小写的)。
但是,MDN docs 将该方法描述为Document.write();(“D”为大写),当我尝试对其进行测试时它不起作用。
谁能帮忙解释一下为什么会这样?
【问题讨论】:
标签: javascript dom document
在向 HTML 中写东西时,我们通常使用:document.write();(“D”是小写的)。
但是,MDN docs 将该方法描述为Document.write();(“D”为大写),当我尝试对其进行测试时它不起作用。
谁能帮忙解释一下为什么会这样?
【问题讨论】:
标签: javascript dom document
同样你可能会看到有人引用Array.find(实际上.find 只存在于Array.prototype),.write 存在于 Document 的 prototype 上,而不是文档构造函数本身。
console.log(Document.prototype.hasOwnProperty('write'));
document.write 有效,因为 document 继承自 Document.prototype。
MDN 对Document.write 的使用旨在表明.write 可以在Document 的任何实例上调用,即使文档构造函数本身没有该属性。
如果您愿意,可以从原型中调用.write:
Document.prototype.write.call(
document, // call on *this HTML document*
'<div>foobar</div>' // first argument passed to .write
);
【讨论】:
.write; new Document 还不够。 (是的,奇怪的是 .write 存在于 Document 而不是 HTMLDocument 中)如果需要,您可以使用 createHTMLDocument 之类的东西