Passing a pointer/reference to a variable as parameter

后端 未结 5 1753
情话喂你
情话喂你 2021-01-24 17:40

I know this question has been asked multiple times (yes, I did some research) but I can\'t see to find a solution that fits my needs.

What I have done so far:

5条回答
  •  别那么骄傲
    2021-01-24 18:24

    What you've described wanting to do doesn't immediately say "use a reference to a variable" to me (as Teemu points out, sounds like you want debouncing), but answering your question about references to variables...

    JavaScript doesn't have any form of references to variables (other than through closures, which might be problematic here). But you can readily do what you're talking about by just using an object and using a property on it. The property is the "variable."

    Simple example:

    function foo(obj) {
      var counter = 0;
      var timer = setInterval(function() {
        console.log("foo: " + obj.property);
        if (++counter === 5) {
          clearInterval(timer);
        }
      }, 500);
    }
    
    var o = {property: "unchanged"};
    // Give the "reference" to `property` to `foo`:
    foo(o);
    
    // Update it periodically while `foo` is doing its asynchronous thing
    setTimeout(function() {
      o.property = "update 1";
    }, 1000);
    setTimeout(function() {
      o.property = "update 2";
    }, 1700);

提交回复
热议问题