gpt4 book ai didi

javascript - 在函数内显式定义变量范围与闭包

转载 作者:行者123 更新时间:2023-12-03 12:33:36 25 4
gpt4 key购买 nike

我有“phone_dlg_manager”构造函数及其私有(private)方法 showinit_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() 初始化多个对话框,而不仅仅是一个对话框。但如果这不太可能是必要的,那么选项 2 也不是没有道理。

关于javascript - 在函数内显式定义变量范围与闭包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23826085/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com