Javascript 在编写jquery插件时,如何从另一个方法调用我的主要插件方法之一?

Javascript 在编写jquery插件时,如何从另一个方法调用我的主要插件方法之一?,javascript,jquery,plugins,Javascript,Jquery,Plugins,我遵循jquery网站上插件创作的指导原则,但我很难弄清楚如何从同一插件中的另一个方法调用主插件方法 我有一个这样的插件: (function($){ var methods = { init: function(options) { var settings = {}; //this == context element of plugin, already jquery return this.each(function() {

我遵循jquery网站上插件创作的指导原则,但我很难弄清楚如何从同一插件中的另一个方法调用主插件方法

我有一个这样的插件:

(function($){
var methods = {
    init: function(options) {
        var settings = {};

        //this == context element of plugin, already jquery
        return this.each(function() {
            var $this = $(this);
            if( options ) {
                settings = $.extend({}, settings, options);
            }
            var data = $this.data('PluginData');
            if(!data) {
                //set up                    
            }

        });
    },
    some_fn: function() {
        //do some stuff
    },
    another_fn: function() {
        //do other stuff, then somehow call some_fn(), maybe via methods.some_fn() ?    
    }
};

jQuery.fn.SomePlugin = 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 {
        console.log('there was an error');
    }
};
})(jQuery);
这几乎就是jquery中的框架代码。然而,我遇到的问题是找出创建“实用程序”函数的最佳方法,该函数仅适用于我的插件方法,或者如何从一个插件方法调用另一个插件方法

例如,在我的插件中,我有3个方法,
init
一些方法和
另一个方法。当我调用
$('#el').SomePlugin('other_fn')
,在
other_fn
中,我想调用
some_fn
。我该怎么做?调用
方法。一些方法可能会起作用,但是,这取决于方法对象中定义方法的顺序,对吗?所以我可以从
另一个\u fn
中调用
某个\u fn
,但反之亦然

另外,创建插件中所有方法都可以使用的实用函数的正确方法是什么,这样我就不会弄乱全局名称空间?我是否只是在我的插件开始时定义实用程序函数,就在调用var方法之前


编辑:多亏了Matt Ball,我已经确认了这些方法。有些方法确实可以调用其他主要方法。现在我只想知道创建(私有)实用程序函数的最佳实践是什么 他们为你的问题提供了确切的例子。:)

对于您的示例,您可以利用
init
函数的作用域:

(function($){
var methods = {
    init: function(options) {
        var settings = {};

        var privateMethod = function(){ ... }

        //this == context element of plugin, already jquery
        return this.each(function() {
            var $this = $(this);
            if( options ) {
                settings = $.extend({}, settings, options);
            }
            var data = $this.data('PluginData');
            if(!data) {
                //set up                    
            }

        });
    },
    some_fn: function() {
        //call private function
        privateMethod()
        // do some stuff
    }
};

jQuery.fn.SomePlugin = 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 {
        console.log('there was an error');
    }
};
})(jQuery);

当我开始使用jq编写插件时,我的生活发生了变化。我知道这不是你问题的直接答案,但值得一看。”……这取决于方法在方法对象中定义的顺序,对吗?“如果我理解你的问题,答案是不,它不是顺序依赖的。你是对的,它似乎是方法。有些方法确实有效,因此回答了我的部分问题。