[英]Explicitly scope a variable inside a function vs closure
我有'phone_dlg_manager'構造函數,它的私有方法show
和init_country_code_combobox
。 對話框參考保存在phone_dlg
變量中。 show
方法觸發init_country_code_combobox
,我有兩個選擇:
1)明確傳遞init_country_code_combobox
方法需要的變量country_combobox
:
function phone_dlg_manager(ctx, open_dlg_button, edit_ctrl, item)
{
var phone_dlg;
show();
function show()
{
phone_dlg = ctx.application.ui.create_dialog(0, "PhoneEditorDlg");
init_country_code_combobox(phone_dlg.country);
read_to_dialog_controls(this._form_item);
phone_dlg.visible = true;
}
function init_country_code_combobox(country_combobox)
{
country_combobox.items.clear();
country_combobox.items.start_adding();
country_combobox.items.finish_adding();
}
}
2)由於可以通過閉包通過phone_dlg
訪問init_country_code_combobox
,因此無需顯式傳遞變量即可訪問所需的屬性:
function phone_dlg_manager(ctx, open_dlg_button, edit_ctrl, item)
{
var phone_dlg;
show();
function show()
{
phone_dlg = ctx.application.ui.create_dialog(0, "PhoneEditorDlg");
init_country_code_combobox(phone_dlg.country);
read_to_dialog_controls(this._form_item);
phone_dlg.visible = true;
}
function init_country_code_combobox()
{
var country_combobox = phone_dlg.country;
country_combobox.items.clear();
country_combobox.items.start_adding();
country_combobox.items.finish_adding();
}
}
當閱讀代碼時,第二個選項似乎更容易理解,但是它使init_country_code_combobox
函數知道的更多了。 我應該選擇哪個選項? 謝謝
這主要是風格問題。 選項1更加init_country_code_combobox()
,而且可擴展性更高,因為您可以使用init_country_code_combobox()
初始化多個對話框,而不僅僅是一個對話框。 但是,如果這不太可能是必需的,則選項2並非沒有道理。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.