For reasons which shall not be enumerated here, I’ve found it potentially useful to attach functions to the window object. However, I’ve discovered rather weird behavior.
<html><head><script>
function sideEffect() { console.log("Side effect happened. Wewt."); }
window.foo = function() {
sideEffect();
return true;
}
window.bar = function() {
sideEffect();
}
</script></head>
<body>
<a href="javascript:window.foo();">Replaces entire window with "true"</a>
<br />
<a href="javascript:window.bar();">Doesn't</a>
</body></html>
Why exactly does invoking a function with a return value decide to replace the window’s contents? This happens in Firefox and Opera, but not in IE9, Chrome, or Safari (all tested on Win7).
So the question is this: Is there some sort of documentation that specifies this behavior?
Or is this a (known) bug in FF/Opera?
[edit] Interestingly (according to answers and comments thusfar) it appears that the abuse of the window object is a red herring here.
Your code is working perfectly–the browser is doing exactly what you are telling it to do.
JavaScript lines are valid in the URL bar of web browsers, and the browser will execute them immediately. (Try it: write an alert box in the URL bar, hit enter, and see what happens.) By writing your JavaScript into the
hrefof your anchor tags, you are setting the location of the browser (in other words, the URL) to that line of JavaScript. Because one of your functions returns a value, the document is over written by that value; this is normal browser behavior.