javascript function name cannot set as click?

The string values of “onfoo” handler attributes are interpreted as the bodies of handler functions. In other words, it’s as if the string value of the attribute is passed to new Function("event", str) with the result being the handler function used.

Additionally, the lexical scope of the function is established as follows, taken from the HTML5 spec (which I consult only in its capacity of a comprehensive description of browser behavior):

Lexical Environment Scope
* Let Scope be the result of NewObjectEnvironment(the element’s Document, the global environment).
* If the element has a form owner, let Scope be the result of NewObjectEnvironment(the element’s form owner, Scope).
* Let Scope be the result of NewObjectEnvironment(the element’s object, Scope).

Thus it’s as if there are up to two nested with blocks implicitly wrapped around the code. Thus in this case the effect is that of calling this:

var handler = new Function("event", "with (this) { click(); }");

Because there’s a “click” method on the DOM element corresponding to the <button>, that function is what’s called by the handler, not the global one established by the script tag. If the “onclick” attribute is set to “window.click();” then the page works properly.

Leave a Comment