jquery插件中的本地方法和名称空间
我创建了一个插件,但我想确定我如何使用“本地”函数 下面是我所做的示意图:jquery插件中的本地方法和名称空间,jquery,variables,jquery-plugins,plugins,private-methods,Jquery,Variables,Jquery Plugins,Plugins,Private Methods,我创建了一个插件,但我想确定我如何使用“本地”函数 下面是我所做的示意图: (function($) { var methods = { init : function( options ) { // CODE ... // Call of a local function _test( this ); // CODE ..... }, destroy : function( ) {
(function($) {
var methods = {
init : function( options ) {
// CODE ...
// Call of a local function
_test( this );
// CODE .....
},
destroy : function( ) {
// CODE .....
_test( this );
// CODE .....
}
};
function _test( container ) {
// My code : example :
$(container).append("<div id='myplugin'></div>");
}
$.fn.myplugin = function( method ) {
if ( methods[method] ) {
return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
}
else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
}
else {
$.error( 'Method ' + method + ' does not exist on jQuery.myplugin' );
}
};
})(jQuery);
(函数($){
var方法={
初始化:函数(选项){
//代码。。。
//局部函数的调用
_试验(本);
//代码。。。。。
},
销毁:函数(){
//代码。。。。。
_试验(本);
//代码。。。。。
}
};
功能测试(容器){
//我的代码:示例:
$(容器)。追加(“”);
}
$.fn.myplugin=函数(方法){
if(方法[方法]){
返回方法[method].apply(this,Array.prototype.slice.call(arguments,1));
}
else if(typeof方法=='object'| |!方法){
return methods.init.apply(这是参数);
}
否则{
$.error('Method'+Method+'在jQuery.myplugin上不存在);
}
};
})(jQuery);
正如您所看到的,我没有直接将代码插入到方法函数中,而是插入到其他函数中。_函数可以看作是插件的本地函数还是私有函数?我不能成功地在插件之外调用它们,所以对我来说,它们可以被视为私有函数
我是否总是要将代码直接放在methods对象的函数中?
如何声明将在多个方法中使用的函数
那么名称空间呢?我真的不明白
谢谢 因为您公开了methods对象的所有方法,所以该对象的任何部分都不会是私有的。但是,在另一个函数中声明的任何函数的作用域都是声明函数,因此,如果您不以其他方式使该函数可访问,则该函数将是私有的。我不确定是否了解所有内容。@bastien您不了解哪些部分?我知道声明函数中的函数是私有的。我的方法对象的methid是公共的,以便在我的网页代码中调用。但是,我不明白为什么我在method对象的方法中调用的函数不是私有的。。。我认为直接从插件外部调用它们是不可能的。此外,如果我想在method对象的多个方法中使用函数,那么解决方案是什么?@bastien在您的代码中,您只需转发调用,因此您封装的唯一内容就是被调用函数的名称。我可能没有为答案输入正确的名称。想象一下,我没有使用init方法中的_init(),而是使用函数test(),它也将用于destroy方法。所以我需要在方法对象之外声明测试函数。不还是有其他方法可以做到这一点?