简体   繁体   English

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

[英]Changing variable inside settimeout inside another function

I'm trying to create reusable function that has settimeout function inside that will change the variable passed to the first function. 我正在尝试创建内部具有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);

You can't. 你不能 When you do 当你做

reusableFunction(variable);

the value of variable is passed into the function, not the variable itself. variable传递给函数,而不是变量本身。 The parameter passedVariable is not in any way connected to variable . 参数passedVariable完全不连接到variable That is, you end up with something like this in memory: 也就是说,您最终会在内存中看到以下内容:

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

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

You could pass in an object and have the function update a property on it instead: 您可以传入一个对象,然后让该函数更新其属性:

let obj = {
    prop: true
};

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

reusablefunction(obj);

With that, you end up with something like this in memory: 这样,您最终会在内存中得到以下内容:

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

Since both obj and passedObject refer to the same object, you can change its properties via either of them. 由于objpassedObject引用同一个对象,因此可以通过它们两者之一来更改其属性。


That said, there may well be a better way to solve the underlying problem you're trying to solve... 也就是说,可能有更好的方法来解决您要解决的根本问题...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM