0

我很难从插件本身调用公共方法。我不确定问题是什么。我究竟做错了什么?

(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);
4

3 回答 3

2

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

var MyPlugin = function(){
    var self = this;
    ...
    var privatefunction = function () {
        self.publicFunction();
    }
...
于 2012-09-14T15:51:44.480 回答
1

在您的 MyPlugin 函数中缓存对 MyPlugin 实例的引用:

var self = this;

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

self.publicFunction();

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

于 2012-09-14T15:51:34.330 回答
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);
于 2012-09-14T16:06:28.817 回答