Given this code:
<button id="blah" onclick="alert(id)">Click me</button>
Clicking the button will alert "blah". Why does the id
attribute become a variable visible within the scope of the onclick
handler?
Another example:
<button style="font-size:200%" onclick="console.log(style)">Click me</button>
Here we see that style
refers to a CSSStyleDeclaration
object, rather than the string value of the attribute. This is similar to what we'd get by referencing an index of the button element's attributes
property, or through attribute properties like this.style
(getAttribute
would return the string value instead).
Where is this behavior specified?
http://jsfiddle.net/b8mpJ/
Because it's specified in Web Applications API. Quoting whatWG's Living Standard:
When the user agent is to get the current value of the event handler H, it must run these steps:
[...] Using the script execution environment obtained above, create a function object with:
[...] Lexical Environment Scope
Let Scope be the result of NewObjectEnvironment(document, 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).
NewObjectEnvironment() is defined in ECMAScript edition 5 section 10.2.2.3. You may probably know its effect better from with statement (where it's used as well). In other words, the target element's properties are checked as well when looking for a particular name binding in the event handler's function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With