Max Koretskyi
Max Koretskyi

Reputation: 105563

Explicitly scope a variable inside a function vs closure

I have the 'phone_dlg_manager' constructor function and its private methods show and init_country_code_combobox. The dialog reference is held in the phone_dlg variable. The show method triggers init_country_code_combobox and I have two options:

1) Explicitly pass the variable country_combobox that the init_country_code_combobox methods needs:

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) Since phone_dlg is accessible withing init_country_code_combobox through closure, I can access the property that I need without explicitly passing the variable:

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

The second option seems easier to understand when reading code, however it makes the init_country_code_combobox function know more than it needs. Which option should I choose? Thanks

Upvotes: 0

Views: 39

Answers (1)

Barmar
Barmar

Reputation: 782775

This is mostly a matter of style. Option 1 is a little cleaner, and more extensible, since you can use init_country_code_combobox() to initialize more than just the one dialog. But if this is unlikely to be necessary, option 2 is not unreasonable.

Upvotes: 1

Related Questions