[英]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? 一个人在使用javascript时会遇到什么样的问题和陷阱(
<script src="sample.js" type="text/javascript><script>
),以及如何避免它们?
I'm asking this because I just ran into an issue where I wrote my javascript code inside a velocity template file which is included in an overall layout template. 我问这个问题是因为我刚遇到一个问题,我在整体布局模板中包含的速度模板文件中编写了JavaScript代码。 The layout template has many different javascript included.
布局模板包含许多不同的javascript。 My javascript code works just fine on a page by itself, but when included with the layout template, it started to break.
我的JavaScript代码本身在页面上就可以正常工作,但是当包含在布局模板中时,它开始崩溃。 (No javascript errors, but things weren't working).
(没有javascript错误,但无法正常运行)。
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.
在这种情况下,最好的选择是将所有代码移到名称空间中,这意味着创建一个对象或匿名函数来容纳您编写的javascript代码。
for example instead of just doing 例如,而不只是做
var myWord = 'hello!';
alert(myWord);
where the name myWord
might already be in use, you could do 您可能已经在使用
myWord
这个名称了
(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. 您只需要确保
myUniqueNamespace
确实是唯一名称,就可以在其中添加任何您喜欢的名称作为属性。
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). myWord
存在于用于创建myUniqueNamespace
的匿名函数的范围内,因此您不能直接从外部进行操作(类似于其他语言中的private成员)。 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. 然而该方法
sayWord
在相同的范围内被定义myWord
和关闭在其上,这意味着获得myWord
保持在确定指标的方法内。 that might not be the clearest explanation but I hope the example makes it clear. 也许这不是最清楚的解释,但我希望这个例子能使之清楚。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.