Print

Print


Peter C. Chapin wrote:
> On Mon, 26 Oct 2009, Nick Husher wrote:
> 
>> // C-like language:
>> int i = 5;
>> if(1==1) {
>> 	int i = 10;
>> 	printf("%d\n", i); // prints "10"
>> }
>> printf("%d\n", i); // prints "5"
>>
>> // Javascript
>> var i = 5;
>> if(true) {
>> 	var i = 10;
>> 	console.log(i); // prints "10"
>> }
>> console.log(i); // prints "10"
> 
> Everyone's notion of what is intuitive is different. To me the C behavior
> is entirely intuitive. I find the Javascript example to be rather odd. I
> interpret 'int i = 10' as the creation of a new variable. I don't want
> modifications to this variable to impact other variables in a more global
> scope (that I might not know about) just because they happen to have the
> same name. To me that's a recipe for disaster.
> 
It's a recipe for disaster if you try to program complex things without 
using the object and functional paradigms as much as possible.

> #include <someheader.h>  // Contains a declaration of 'i'.
> 
> void f()
> {
>   if (x == y) {
>     int i = 10;  // This must not modify any other variable named 'i'
>     // etc...
>   }
> }
> 
> When I assign 10 to my 'i' the last thing I want to worry about is the
> possibility that I might have modified a global variable defined in a
> header I didn't write.

Fortunately Javascript has singletons, which we can use in place of 
namespaces. Otherwise, the (function(){code}())-wrapper generally is 
used for hiding everything that doesn't need to be accessed from your code.

I'm going to take a wild guess that you may have not of heard of what a 
closure is.

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.

> 
> Peter
> 
>