Luc*_*eis 39
lpfavreau提供了使用您自己的方法扩展 jQuery对象的解决方案(以便它们的功能适用于实际的jQuery对象上下文).
如果您只想命名代码,可以使用美元符号,如下所示:
$.myNamespace = { .. };
Run Code Online (Sandbox Code Playgroud)
或者"jQuery":
jQuery.myNamespace = { .. };
Run Code Online (Sandbox Code Playgroud)
小心你选择的命名空间,因为这可以覆盖现有的jQuery方法(我建议先在jQuery代码中搜索,这样你就不会).
您可以点击此链接:http://www.zachleat.com/web/2007/08/28/namespacing-outside-of-the-yahoo-namespace/
看看创建自己的函数来复制YUI的作用是多么容易:
// include jQuery first.
jQuery.namespace = function() {
var a=arguments, o=null, i, j, d;
for (i=0; i<a.length; i=i+1) {
d=a[i].split(".");
o=window;
for (j=0; j<d.length; j=j+1) {
o[d[j]]=o[d[j]] || {};
o=o[d[j]];
}
}
return o;
};
// definition
jQuery.namespace( 'jQuery.debug' );
jQuery.debug.test1 = function()
{
alert( 'test1 function' );
};
jQuery.debug.test2 = function()
{
alert( 'test2 function' );
};
// usage
jQuery.debug.test1();
jQuery.debug.test2();
Run Code Online (Sandbox Code Playgroud)
Wil*_*ilk 10
这就是我为插件创建名称空间的方法:
(function ($) {
// do not overwrite the namespace, if it already exists
$.MyNamespace = $.MyNamespace || {};
$.MyNamespace.MyPlugin = function () {/*here's the logic*/}
})($);
Run Code Online (Sandbox Code Playgroud)
然后:
$.MyNamespace.MyPlugin ();
Run Code Online (Sandbox Code Playgroud)