Is “clear” a reserved word in Javascript?

后端 未结 4 1827
粉色の甜心
粉色の甜心 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:08

    As the others said, clear is not a reserved keyword. It seems that the called function is document.clear [MDN]. Invoking

    console.log(clear === document.clear);
    

    inside the event handler returns true.

    DEMO

    So it seems, document is in the scope chain of the event handler.... the question now is why.

    JavaScript: The Definitive Guide says:

    In an event handler as HTML attribute, the Document object is in the scope chain before the Window object (...)

    As your method is global, meaning it is a property of the window object, it is not found in the scope chain, as document.clear comes earlier in the scope chain.

    I haven't found any specification for this. The guide also says that one should not rely on that, so I assume this is nothing official.

    If you have form elements inside a form, then even the corresponding form element will be in the scope chain (not sure whether this holds for all browsers though). This is another reason for confusion.


    There are two (not exclusive) ways to avoid such situations:

    • Don't use inline event handlers. It is considered bad practice as it is mixing logic and presentation. There are other ways to attach event handlers.

    • Don't pollute the global namespace. Create one object in global scope (with a name you are sure of does not collide with any window or document properties or ids of HTML elements) and assign the functions as properties of this object. Whenever you call a function, you reference it through this object. There also other ways to namespace your code.

提交回复
热议问题