Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do an element's attributes appear in the scope of an inline function?

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/

like image 959
Dagg Nabbit Avatar asked Dec 24 '13 21:12

Dagg Nabbit


1 Answers

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.

like image 141
raina77ow Avatar answered Oct 08 '22 02:10

raina77ow