开发者

javascript includes problems and pitfalls

What kind of problems and pitfalls can one encounter while doing javascript includes (<script src="sample.js" type="text/javascript><script>) and how to avoid them?

I'm asking this because I just ran int开发者_高级运维o an issue where I wrote my javascript code inside a velocity template file which is included in an overall layout template. The layout template has many different javascript included. My javascript code works just fine on a page by itself, but when included with the layout template, it started to break. (No javascript errors, but things weren't working).


sounds like you're having a collision of global objects. your best bet in this scenario is to move all your code into a namespace, by which I mean create an object or anonymous function to house the javascript code you've written.

for example instead of just doing

var myWord = 'hello!';
alert(myWord);

where the name myWord might already be in use, you could do

(function() {
    var myWord = 'hello!';
    alert(myWord);
})();

or if you need things to persist,

var myUniqueNamespace = new (function() {
    this.myWord = 'hello!';
})();
alert(myUniqueNamespace.myWord);

where you only need to ensure that myUniqueNamespace is indeed a unique name, and you can add whatever names you like as properties to it.

re closure comment: not quite, but we can make it one like this

var myUniqueNamespace = new (function() {
    var myWord = 'hello!';
    this.sayWord = function() { return myWord; };
})();
alert(myUniqueNamespace.sayWord());

myWord exists within the scope of the anonymous function used to create myUniqueNamespace, so you can't get do it directly from the outside (similar to a private member in other languages). however the method sayWord is defined in the same scope as myWord and closes over it, meaning that access to myWord is maintained within the method defintion. that might not be the clearest explanation but I hope the example makes it clear.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜