我在一个文件中有类似的东西,比如test.js:
(function($){
$.test= function(){
alert('test');
}
})(jQuery);
jQuery.test();现在,如果在我的页面中两次加载test.js,即在两个不同的位置加载src=test.js,它就会发出两次警告。我希望它像一个单例。对如何实现这一点有什么想法吗?
发布于 2011-02-14 16:22:28
使用条件快捷方式:
(function($){
!$.test && $.test= function(){
alert('test');
}
})(jQuery);
jQuery.test();如果未定义$.test并且在执行&&之后右侧的代码为&&,则&&的计算结果为true。否则,它将跳过该部分。另一个有用的模式可能类似于:
$.test = $.test || function() {
alert('test');
}这实际上做了同样的事情。如果已经定义了$.test,则使用它,否则将匿名函数分配给$.test。这两个版本都可以(也可能应该)进行优化,但不仅要检查它们是否已定义,而且还要检查它们是否来自function类型。
发布于 2011-02-14 16:20:04
你试过这样的东西吗?
if(typeof $.test == "undefined") {
(function($){
$.test= function(){
alert('test');
}
})(jQuery);
jQuery.test();
}发布于 2011-02-14 16:20:06
(function($){
$.test = function() {
if (!$.test.hasBeenRun) {
$.test.hasBeenRun = true;
alert('test');
}
}
$.test.hasBeenRun = false;
})(jQuery);
jQuery.test();https://stackoverflow.com/questions/4990028
复制相似问题