Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Chrome use `with` for inline events

If you take a look at this fiddle in Chrome and click the Trigger text with the js console open you will see this:

enter image description here

What is the reason of all those with blocks and what is it's value?

like image 230
MosheK Avatar asked Jan 14 '13 19:01

MosheK


2 Answers

It looks to me as if it's how the browser creates a function for the event handler when it's specified as an HTML "onclick" attribute. I think what that does is:

  • make an event handler function with a single parameter for the event object and your supplied code;
  • make properties of the element (the <a> tag), an empty object (?), and the document object appear to be available symbols for the code in that function.

That is, this[0] is the <a> element itself, this[1] looks like an empty Object instance, and this[2] is the document object. What this means is that in code you write as part of an "onfoo" event handler attribute (and not code in any ordinary event handler bound from straight JavaScript code), it's possible to refer to the properties of the target element (the element for which you're setting the attribute) and the properties of the document element as if they were present in the scope chain.

If you change the code a little:

$('<a href=# onclick="console.log(baseURI);"> ...

then you get the value of the "baseURI" property of the <a> element. No need to prefix "baseURI" with anything that explicitly refers to the DOM node for the <a> element; it's just "there" as if it were declared with var in some enclosing scope.

(checking w3c specs now ...) edit — I haven't found anything that stipulates what symbols are supposed to be available to the script code in event handlers. This is really weird.

edit again — Firefox seems to do the same thing, though I don't see the explicit with statements anywhere.

like image 151
Pointy Avatar answered Oct 03 '22 13:10

Pointy


with moves it's argument on top of scope stack. So it's even higher than global object, function params, etc. No idea why they use it. Perhaps it is a generated code.

like image 22
Ondra Žižka Avatar answered Oct 03 '22 13:10

Ondra Žižka