I just spent a long time figuring out that I shouldn\'t use clear() as the name of a function in Javascript:
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
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.
If form owner is not null, let Scope be the result of NewObjectEnvironment(form owner, Scope).
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
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);