代码之家  ›  专栏  ›  技术社区  ›  GulgDev

为什么不将属性设置为无效值?

  •  0
  • GulgDev  · 技术社区  · 10 月前

    根据WebIDL规范的定义,在接口上设置属性应将JS值转换为其IDL等效值。明确指出,如果值无法转换,则应抛出TypeError。

    但为什么这不是投掷,而是默默地失败?

    document.onvisibilitychange = 4;
    console.log(document.onvisibilitychange); // null
    
    1 回复  |  直到 10 月前
        1
  •  1
  •   Kaiido NickSlash    10 月前

    IDL定义 Document#onvisibilitychange

    attribute EventHandler onvisibilitychange;
    

    EventHandler 其本身被定义为

    [LegacyTreatNonObjectAsNull]
    callback EventHandlerNonNull = any (Event event);
    typedef EventHandlerNonNull? EventHandler;
    

    在哪里? LegacyTreatNonObjectAsNull 是:

    如果[ LegacyTreatNonObjectAsNull ] extended attribute 出现在a callback function ,则表示分配给 attribute 其类型为 nullable 回调函数 将被更宽松地转换:如果值不是对象,它将被转换为null,如果值不是 callable ,它将被转换为 回调函数 值在调用时什么也不做。

    这里的值不是对象,因此它被视为 null 。不会抛出错误。


    其他更严格的属性会抛出,例如 <input> s files attribute ,其定义为

    attribute FileList? files;
    

    如果你把它设置成除了a之外的任何东西,它都会扔 FileList 对象:

    document.querySelector("input").files = 0;
    <input>
    推荐文章