i have following code in html file:
<script type="text/javascript"> window.never = function() { console.log('this function never called'); } (function(d, s, id){ var js, srjs = d.getelementsbytagname(s)[0]; if (d.getelementbyid(id)) {return;} js = d.createelement(s); js.id = id; js.src = "this.script.does.not.exist.js"; srjs.parentnode.insertbefore(js, srjs); }(document, 'script', 'streamrail-jssdk')); </script>
see fiddle: http://jsfiddle.net/sebvaeja/
looking @ console, can see window.never
function called ('this function never called' written console).
when debugging chrome dev tools, see in call stack caller closure (first line: http://jsfiddle.net/sebvaeja/
).
if change never function off global scope:
function never() { console.log('this function never called'); }
then not being called.
can please explain why window.never function being called? triggering call? guess it's got function being on window object, can't see reasoning behind that.
the function expression followed parenthesis:
window.never = function() { ... } (...)
the line break after function expression not terminate variable statement, parser that's function call:
function() { ... }(...)
in fact, using same technique here:
(function(d, s, id){ // ... }(document, 'script', 'streamrail-jssdk'))
that's function expression followed (...)
, calls function.
solution: add semicolon after definition , good.
if change never function off global scope ... not being called.
in case function definition interpreted function declaration, not expression. function declaration more statement , therefore cannot part of callexpression. following parenthesis therefore interpreted grouping operator (like intended).
Comments
Post a Comment