Monday 1 January 2018

javascript - When do I use var?












My
understanding it that with in a function if I use var then I have a local variable. If I
do not delcare var I now have a global
variable.



But what about oustide of functions,
what effect does var have?


itemprop="text">
class="normal">Answer



First of
all, it's generally bad practice to use code outside of functions. If nothing else, wrap
your code in anonymous
functions:



(function(){

//
code
})();


As
for what effect var has, it "declares" a
variable:



var
foo;
alert(foo); //
undefined;


vs:



alert(foo);
// error: foo is not
defined


The reason for
this is that the above code is functionally identical
to:



alert(window.foo);


without
declaring the variable with var, you get a lookup error, the
same as trying to access the property of any object that doesn't
exist.



Note that one of the oddities of
var is that all declarations are pulled to the top of the
script, so this will work as
well:



alert(foo); //
undefined
var
foo;


You will also
have access to your variable in the window object (though you
will also have this by setting the variable without var, e.g. just
foo=42):



var
foo;
for(var key in window){
// one of these keys will be
'foo'
}


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...