在另一个函数内的settimeout中更改变量

时间:2019-07-30 16:05:08

标签: javascript

我正在尝试创建内部具有settimeout函数的可重用函数,该函数将更改传递给第一个函数的变量。

let variable = true;


reusablefunction = (passedvariable) => {


    setTimeout(() => {

        passedvariable = false;
       // this turns out true for some reason

    }, 1, passedvariable);
  };



// Change value of passed variable (variable) to false after a timeout 

reusablefunction(variable);

1 个答案:

答案 0 :(得分:2)

不能。当你做

reusableFunction(variable);
variable

被传递给函数,而不是变量本身。参数passedVariable没有以任何方式连接到variable。也就是说,您最终会在内存中看到以下内容:

+−−−−−−−−−−−−−−−−−+
| variable: false |
+−−−−−−−−−−−−−−−−−+

+−−−−−−−−−−−−−−−−−−−−−−−+
| passedVariable: false |
+−−−−−−−−−−−−−−−−−−−−−−−+

您可以传入一个对象,然后让该函数更新其属性:

let obj = {
    prop: true
};

let reusablefunction = (passedObject) => {
    setTimeout(() => {
        passedObject.prop = false;
    }, 1); // No need to pass the parameter here
};

reusablefunction(obj);

这样,您最终会在内存中得到以下内容:

+−−−−−−−−−−−−−−−+              
| obj: Ref55461 |−−−−−−−−−−−−−+
+−−−−−−−−−−−−−−−+             |
                              |          +−−−−−−−−−−−−−+
                              +−−−−−−−−−>|   Object    |
                              |          +−−−−−−−−−−−−−+
+−−−−−−−−−−−−−−−−−−−−−−−−+    |          | prop: false |
| passedObject: Ref55461 |−−−−+          +−−−−−−−−−−−−−+
+−−−−−−−−−−−−−−−−−−−−−−−−+

由于objpassedObject都引用相同的对象,因此您可以通过它们之一来更改其属性。


也就是说,可能有更好的方法来解决您要解决的潜在问题...