JavaScript Tip: Running code in the dark
JavaScript Tip: Running code in the dark: "At a recent client, we were finding strange behaviour occuring in the JavaScript side of the house.
After taking a look, the problem was namespace collisions.
A couple of the developers were new to JavaScript, and didn’t know about the scoping world.
For example, the classic:
var foo = 'whee';
when placed at the top level of a script, and run in a browser, will actually set a variable on the scope that it is in, which is “window”.
You can simply test this with:
var foo = 'whee';
alert('foo = ' + foo);
alert('window.foo = ' + window.foo);
As such, the project was polluting the window object with everything under the sun, and there were conditions in which clashes occured.
We quickly fixed this with the lovely trick:
(function() {
// do you stuff here!
})();
You can make sure that the namespace is save with another simple example:
(function() {
var foo = 'whee';
alert('inside: ' + foo);
})();
alert('outside: ' + foo); // no var foo!
"

0 Comments:
Post a Comment
<< Home