jQuery插件 - 从插件中调用公共方法

时间:2012-09-14 15:48:15

标签: javascript jquery jquery-plugins

我在插件本身中调用公共方法时遇到了困难。我不确定是什么问题。我做错了什么?

(function($) {

    var MyPlugin = function(){

        /* PUBLIC */
        this.publicFunction = function() {
            // Do public things
        };

        /* PRIVATE */
        var privateFunction = function() {
            // Do private things

            // Call this one public function
            publicFunction(); // WANT THIS but doesn't work
        }
    };

    $.fn.myPlugin = function() {

        var myPlugin = new MyPlugin(options);

        // Binding click to public function
        $("a").bind('click', function(e){
            e.preventDefault();
            myPlugin.publicFunction($(this)); // AND WANT THIS but does
        });

        return myPlugin;
    };
})(jQuery);

3 个答案:

答案 0 :(得分:2)

您只需要能够在函数内引用MyPlugin的this对象,而不会丢失范围。为此,请将其分配给变量(名称无关紧要,典型约定为self

var MyPlugin = function(){
    var self = this;
    ...
    var privatefunction = function () {
        self.publicFunction();
    }
...

答案 1 :(得分:1)

在MyPlugin函数内部缓存对MyPlugin实例的引用:

var self = this;

然后在privateFunction内部调用publicFunction作为self的成员:

self.publicFunction();

问题是你已经将publicFunction定义为MyPlugin实例的成员,而不是全局(这是好的),但是你从不同的范围调用它,因为publicFunction不是全局的,你需要告诉javascript在哪里找到它。您无法使用this,因为在您调用它的上下文中,this不会指向MyPlugin实例

答案 2 :(得分:0)

(function($) {

    var MyPlugin = function(options){

        /* PRIVATE - one copy for each instance */
        var options = $.extend({},options),
            privateFunction = function() {
                // Do private things
                // ...
                // Call this one public function
                this.publicFunction();
            };
    };

    // Shared by all MyPlugin instances;
    MyPlugin.prototype.publicFunction = function($element) {
            // Do public things
    };

    $.fn.myPlugin = function() {

        var myPlugin = new MyPlugin(options);

        // Binding click to public function
        $("a").bind('click', function(e){
            e.preventDefault();
            myPlugin.publicFunction($(this));
        });

        return myPlugin;
    };
})(jQuery);