jQuery 插件外可评估的对象

Object assessible outside jQuery plugin

我有两个 jQuery 插件: 第一个:

;(function($){

    function CbUploader(element,options){
        widget=this;
        .....
    }
    $.fn.cbUploader = function(options){
        new CbUploader(this,options);
        return this;
    }; 
})(jQuery);

第二个:

;(function($){

    function CbGallery(element,options){
        widget=this;
        $('body').on('click',".thumbnail-upload",function(){
             console.log(widget)
        });
    $.fn.cbGallery = function(options){
        new CbGallery(this,options);
        return this;
    };

})(jQuery);

当我点击 .thumbnail-upload div console.log returns CbUploader 对象而不是 CbGallery。为什么插件范围隔离在我的情况下不起作用?

不要全局注册 widget 变量,使用带有 var 的局部变量。就像你做的那样,你使用 window.widget = this 相互覆盖。

function CbGallery(element, options) {
    var widget = this;

    $('body').on('click', '.thumbnail-upload', function() {
        console.log(widget);
    });
}

CbUploader 函数中也做同样的事情。