How to execute some javascript without modifying the global scope? -



How to execute some javascript without modifying the global scope? -

i want phone call javascript code own purposes needs define variables, want isolate doesn't pollute global scope. wrap in anonymous function object, phone call immediately, , don't assign or result anything:

function() { var myinnerhelperfunction = function(object) { //do work }; var anobject = ...; myinnerhelperfunction(anobject); }();

but syntax error: syntaxerror: unexpected token (

you can't invoke function declaration. need create look instead. commonly seen technique accomplish wrap function in parentheses:

(function() { var myinnerhelperfunction = function(object) { //do work }; var anobject = ...; myinnerhelperfunction(anobject); }());

however, note unary operator work (anything causes build parsed expression, rather declaration):

~function example() { console.log("example"); }();

to expand upon further, code throws syntax error because function missing identifier. "program" can contain statements , function declarations. therefore, code must parsed function declaration. function declaration must have identifier. yours doesn't, programme invalid.

when wrap parentheses around function, parse tree different. parentheses parsed "expression statement", can contain expression. since functions can parsed either expressions or declarations, depending on context in appear, legal, , function parsed expression. since function expressions can invoked, works.

javascript

Comments

Popular posts from this blog

web services - java.lang.NoClassDefFoundError: Could not initialize class net.sf.cglib.proxy.Enhancer -

Accessing MATLAB's unicode strings from C -

javascript - mongodb won't find my schema method in nested container -