【问题标题】:What's the difference between JavaScript method Document.write() vs document.write()? [duplicate]JavaScript 方法 Document.write() 与 document.write() 有什么区别? [复制]
【发布时间】:2021-02-21 05:00:13
【问题描述】:

在向 HTML 中写东西时,我们通常使用:document.write();(“D”是小写的)。

但是,MDN docs 将该方法描述为Document.write();(“D”为大写),当我尝试对其进行测试时它不起作用。

谁能帮忙解释一下为什么会这样?

【问题讨论】:

    标签: javascript dom document


    【解决方案1】:

    同样你可能会看到有人引用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
    );

    【讨论】:

    • 你说的我明白了,但还有几个问题:1、我在MDN中找不到document与Document.prototype的关系线索,这种关系本身存在吗? 2,我试过 {new Document().write()} 这也不起作用。 (但 new Document() 是 Document 的一个实例,应该包含 write() 方法); 3、我是一个语言学习新手,希望不要做傻问题。
    • 只有 HTML 文档可以调用 .writenew Document 还不够。 (是的,奇怪的是 .write 存在于 Document 而不是 HTMLDocument 中)如果需要,您可以使用 createHTMLDocument 之类的东西
    猜你喜欢
    • 1970-01-01
    • 2013-09-18
    • 2014-10-16
    • 2014-07-16
    • 2011-02-03
    • 2016-06-11
    • 2011-06-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多