Hello, please sign in or register
You are here: Home

Javascript namespacing conflict resolution

Namespacing in javascript seems to be the consensus of many developers. To quickly update existing code and protecting the funcions within we can wrap them in an anonymous function like so...

(function(){
...
 original code
...
}()

The "()" at the end executes the content the anonymous function, furthermore any functions you assign to other dom elements will know to execute the methods contained within. Whilst none of the methods within will be defined in "window"... as they might have been before.

The one problem that i've found with is with callback methods such as "setTimeout" which breaks out the scope of the anonymous function (gets executed at the global scope). And as none of our functions our defined at the global scope ( to protect them from other code ). The solution is to make our method available at the global scope or define a namespace and add the method to it.

E.g. This will produce an error

(function(){

function myfunc()
{
   alert('Hello');
}
setTimeout('myfunc',1000);
}()

Whilst the following will define the function at the global level (omitting any "var" before the anonymous function declaration). But this is vunerable to being redeclared or overwriting other code.

(function(){

myfunc = function()
{
   alert('Hello');
}
setTimeout('myfunc',1000);
}()

Resources

I haven't really even broken the ice with parameter scopes here. Something which is a powerful (albeit confusing) feature of javascript. I'll hopefully figure it out and write an insightful article not before too long.

http://www.digital-web.com/articles/scope_in_javascript/

Comments

jainbin0510
jainbin0510 rolex watches tiffany outlet hermes bags
Created 10/05/16
Title*
Comment

Prove you are not a robot

To prove you are not a robot, please type in the six character code you see in the picture below
Security confirmation codeI can't see this!
Contact
Name*
Email never shown*
Home Page

Author

Andrew Dodson
Since:Feb 2007

Comment | flag

Categories

Bookmark and Share