首页 > 解决方案 > 使用尚未声明的变量

问题描述

我在理解 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");

a_yet_to_be_defined_var由于未定义,这会在第 1 行产生错误。

看了这篇文章后:我又试了一次,但这次声明了没有价值的 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);,我已经看到了相关问题的箭头函数解决方案,但我不确定如何让它在这里工作。

有可能完成这项工作吗?

标签: javascriptvariablesscope

解决方案


与其定义一个名为 的值easy_to_edit_value,不如将其更改为一个调用的函数,该函数easy_to_call_function将返回"some text "与 的当前值连接的值new_var

一旦分配了(varlet)变量,每次都必须重新分配或重新评估它。

let new_var;
const easy_to_call_function = () => "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_call_function()); // Call the function
}

my_function2("more text");


推荐阅读