2016-11-10 33 views
0

我正在創建我的第一個插件並遇到一些挑戰。我定義了幾個全局變量:默認和選項。我按照如下插件的模式:選項變量未定義

(function ($) { 
    var defaults; 
    var options; 

    $.fn.button_carousel = function(options){ 
    console.debug("initializing button carousel"); 

    defaults = { 
     days_in_month: 0, 
     starting_day: 0, 
     days_with_appointments: null, 
     btnAppointmentFontColor: "#556b2f"   
    }; 



    options = $.extend({}, defaults, options); 

    console.debug("options: days_in_month: " + options.days_in_month + 
       "options: staring_day: " + options.starting_day + 
       "options: days_with_appointments: " + options.days_with_appointments); 
    ... 

    HighlightDays(); 

return this.each(function(){ 
    console.log(options); 
    });  
}; 

function HighlightDays() 
{ 
    if(options.days_with_appointments != undefined && options.days_with_appointments != null) 
    { 
     ... 
    } 
} 
}(jQuery)); 

檢出調試語句。它按預期輸出每個屬性的值。但是,當我調用函數HightlightDays()時,if語句的條件會拋出一個錯誤,指出options變量未定義。怎麼可能?我將其聲明爲全局變量,因此可以隨處訪問。請解釋。

回答

0

但是,當我調用函數HightlightDays()時, if語句的條件拋出錯誤,說明options變量未定義。 這怎麼可能?我將其聲明爲全局變量,因此可以在任何地方訪問 。

optionsundefinedoptions$.fn.button_carousel的實例的範圍內被定義爲$.extend({}, defaults, options),當其被分配給options標識符時,當$.fn.button_carousel()被調用時。

你可以通過optionsHighlightDays()

HighlightDays(options) 

plnkr http://plnkr.co/edit/tqwIzaqin0HFHweE9h41?p=preview

+0

@Alan查看更新後的帖子。 – guest271314

0

添加到來賓的答案,如果你傾向於進一步用它在你的功能,那麼也可以像window.options這樣就可以了在任何地方使用它範圍不會侷限於一個功能。