【发布时间】:2021-07-04 09:09:05
【问题描述】:
我在理解 Javascript 的称为提升的引擎技术时遇到了问题。
我尝试在文件顶部创建var 以快速访问和编辑,但我想使用尚未声明的变量。
第一次尝试:
var easy_to_edit_value = "some text " + a_yet_to_be_defined_var;
//imagine loads of code so its hard to find the correct funtion to edit the log
function my_function (a_yet_to_be_defined_var){
console.log(easy_to_edit_value);
}
my_function("more text");
这会在第 1 行产生错误,因为未定义 a_yet_to_be_defined_var。
看完这篇文章后:post-by-apsillers 我又试了一次,但这次声明了没有价值的 var(所以它是已知的但未定义的,直到在某处声明了 futheron)
var a_yet_to_be_defined_var; // now its known so this error is gone
var easy_to_edit_value = "some text " + a_yet_to_be_defined_var;
function my_function (a_yet_to_be_defined_var){
console.log(easy_to_edit_value);
}
my_function("more text");
//still undefined
//new attempt with a fresh var being set in the function before being called
var new_var;
var easy_to_edit_value = "some text " + new_var;
function my_function2 (a_yet_to_be_defined_var2){
new_var = a_yet_to_be_defined_var2;
console.log(easy_to_edit_value);
}
my_function2("more text");
//still undefined
但是这个输出:some text undefined 我期待 some text more text 因为我在请求之前填充了 var。
请注意,这些函数不是使用 my_function("something") 运行的,而是由以下代码触发的:client.on('message', my_function);,我已经看到了相关问题的箭头函数解决方案,但我不确定如何让它在这里工作。
有没有可能实现这个功能?
【问题讨论】:
-
虽然
a_yet_to_be_defined_var稍后被声明,但它与尝试使用的范围不同,并且仅在my_function的范围内可用。在这种情况下,变量提升不起作用。 -
new_var在被赋予值之前被声明和使用 - 这是明显相同结果的完全不同的原因。
标签: javascript variables scope