Monday, 15 September 2014

html - Var & JavaScript Variable Scope -



html - Var & JavaScript Variable Scope -

js code

var foo = "hello world!"; // <------- global scope document.write("<p>before our anonymous function foo means '" + foo + '".</p>'); (function() { // next code enclosed within anonymous function var foo = "goodbye world!"; // <------- local scope document.write("<p>inside our anonymous function foo means '" + foo + '".</p>'); })(); // phone call our anonymous function document.write("<p>after our anonymous function foo means '" + foo + '".</p>');

html output

before our anomymous function foo means 'hello world!". within our anomymous function foo means 'goodbye world!". after our anomymous function foo means 'hello world!".

my problem

when replace value of foo variable within function why not replaced ? how still contains "hello world!"? if i'm access global variable within function how can ?

by using var foo within function, explicitly telling variable alter locally, within function. if want alter globally, utilize foo = ...

if want read on it, suggest this question

javascript html variables global-variables scope

No comments:

Post a Comment