Is a namespace a must for local JavaScript functions?
I agree that using a namespace is essential for JavaScript libraries, but what about those functions that reside in HTML files in a script
tag? Basically these are "local" functions that are never shared with 开发者_如何学Pythonany other pages. Do you guys still use a namespace for those? If so, do you use the same namespace as your shared custom library?
I would say that a local namespace can help guard against any possible collisions with 3rd party JavaScript libraries, but it need not be imperative.
You don't need a namespace, because as you say, there is no potential naming conflict.
The only potential conflict is if you are importing a library that does not use namespaces, and it introduces a variable which conflicts with a name you placed in the script file. But if you are following the namespaces practice in all the libraries, then it doesn't matter.
First of all. Placing javascripts in HTML is not something you should do. Javascripts should go in separate file(s). With obvious exception of loader, such as head.js or similar, if you use one.
I personally see no need to namespace local scripts. It never happened that one script I wrote collided with any plugin I have used.
While it might not be imperative, there is really no reason NOT to namespace those. It can only help prevent issues.
Here's a good article on Script Junkie about different methods of namespacing: http://msdn.microsoft.com/en-us/scriptjunkie/gg578608.aspx
It has to depend on where the html that the scripts are embedding in is coming from. If it's in a context where the code's controlling the local scripts will be aware of what the other is doing, then I suppose there's no need for a namepace.
If on the other hand, the scripts will be running in the context of something like a CMS then there could be various server side plugins emmitting local javascript without the client side coder necessarily understanding the intricacies of the code. Even there, if that code is all namespaced, then you should be fine. Accidentally forgetting one var
keyword can break a namespace though.
All in all, a namespace doesn't hurt things and isn't that hard. It's a lot easier to maintain and think about javascript when it's not all mixed in with html.
精彩评论