On Mon, 26 Oct 2009, Jacob Beauregard wrote:
> Let's say I write the following in javascript:
>
> var foo = 132;
> (function () {
> alert(foo) //outputs 132
> var bar = 22;
> foo = function () { return bar; };
> }());
>
> alert(bar); //outputs undefined
> alert(foo()); //outputs 22
>
> when you create a function within a function, it will look for the
> variable in its scope first, then the next scope down. So if you didn't
> want people to see bar, you can just wrap it in the
> (function(){code}())-wrapper.
Needing to use an anonymous function to create an inner scope isn't what
I'd call intuitive. In any case the original code looked like this
var i = 5;
if(true) {
var i = 10;
console.log(i); // prints "10"
}
console.log(i); // prints "10"
So I guess Javascript allows you to do things like
var i = 5;
var i = 10; // no error here.
console.log(i); // prints "10"
Is that how it works? Is there any difference between the above and
something like
var i = 5;
i = 10;
console.log(i); // prints "10" still, I would imagine.
As you can tell I don't know Javascript.
Peter
|