Hokay, so I've been debugging a JS issue our app has on some mobile browsers recently, and the revelation the solution gave me seems to be completely insane:
My issue was, on the stock android browser and iOS Safari (nowhere else) when I would call a function on an object, it would return an error, that the object had no such function. I figured, standard mistake... except I was explicitly defining that object & function immediately before - as a pseudo-namespace, as in
var varname = varname || { ... }
Now, 'varname' as a JS object had not been created before, so the || was just for safety as these plugins get called a bunch... but in a way I cant explain, a <section> from earlier on the page, with an id="varname", was in that js object already.
HOW IS THIS POSSIBLE? Maybe it's just late, and I'm overlooking something, but it looks like somewhere my HtmlElements are being assigned to javascript objects with the id as var name.
I've only been coding js for 3.5 years, but either I've found some weird bug, or have to seriously re-evaluate my knowledge of JS.
Here's the exact code for any skeptics (JSTL provides part of the ID, but I don't think that has anything to do with it):
<section id="attr<c:out value="${thisFieldAndAttrs.id}" />" class="attr"> ...
and a few hundred lines later (but without mention of anything attr###), I go to create an object:
var attr<c:out value="${thisFieldAndAttrs.id}"/> = attr<c:out value="${thisFieldAndAttrs.id}"/> || { ...
and the object ALREADY EXISTS, as an instance of the <section> HTMLElement. This happens on all browsers, but newer browsers seem to know enough to overwrite the object (?). The only external script I have is JQuery, and as far as I can tell, if you could just reference HTMLElements by their IDs in Javascript, wouldn't that remove a lot of the convenience of using JQuery in the first place? I've looked in their documentation, and can't find anywhere mentioning this.
Is this a bug? Or just very unexpected functionality? Or am I missing something here...
In some browsers (all?), an element with an ID will automatically generate a property on the window with said Id. However, if you declare the variable, it should override it, however that pretty much breaks what you were doing. I'd suggest declaring it directly on window if it's something that needs to be available to other scripts.
<div id="section"></div>
<script>
console.log(section); // div element
(function(){
var section = section || {};
console.log(section); // object
window.section = section;
})();
console.log(section); // object
</script>
http://jsfiddle.net/8u8sn/3/
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