Is “clear” a reserved word in Javascript?

后端 未结 4 1887
粉色の甜心
粉色の甜心 2020-11-22 02:15

I just spent a long time figuring out that I shouldn\'t use clear() as the name of a function in Javascript:


    

        
4条回答
  •  天涯浪人
    2020-11-22 03:05

    No, clear is not a reserved keyword.

    The problem is that, since you use an event handler content attribute, your global function window.clear is shadowed by the obsolete document.clear.

    This behavior is explained in step 10 of getting the current value of the event handler:

    Lexical Environment Scope

    1. If H is an element's event handler, then let Scope be the result of NewObjectEnvironment(document, the global environment).

      Otherwise, H is a Window object's event handler: let Scope be the global environment.

    2. If form owner is not null, let Scope be the result of NewObjectEnvironment(form owner, Scope).

    3. If element is not null, let Scope be the result of NewObjectEnvironment(element, Scope).

    Note: NewObjectEnvironment() is defined in ECMAScript edition 5 section 10.2.2.3 NewObjectEnvironment (O, E)

    That means that the global scope is shadowed by

    1. The document
    2. The form owner, if any
    3. The element

    Therefore, you can

    • Rename your function.

      function clear__() { document.body.style.background = 'green'; }

      This approach is not completely reliable because some browser could implement a non-standard feature which shadows your variables. Or a future spec could introduce that feature (example).

    • Call your function as a method of the global object.

      For example, assuming window is not shadowed, you can use window.clear.

      function clear() { document.body.style.background = 'green'; }

    • Avoid event handler content attributes.

      Instead, you can use event handler IDL attributes or event listeners.

      function clear() { document.body.style.background = 'green'; }
      document.querySelector('button').onclick = clear;

      function clear() { document.body.style.background = 'green'; }
      document.querySelector('button').addEventListener('click', clear);

提交回复
热议问题