0

In the following code, how is it possible that variable temp is still alive after the call to the Decorate ends?

function Decorate(target, key) {
  let temp = target[key];
  Object.defineProperty(target, key, {
    get: function() {
      console.log('getter executed');
      return temp;
    },
    set: function(newValue) {
      console.log('setter executed');
      temp = newValue;
    }
  });
}

class Test {
  x;
  constructor() {}
};

let t = new Test();

Decorate(t, 'x'); //first and only decorator call after which the variable temp should be dead

t.x = 123;  //setter sets x to 123, obviously it somehow still uses temp

t.x = 256;  //second setter call sets x to 256, temp still somehow alive

t.x = 357;  //etc.
Milan
  • 76
  • 4
  • 1
    Because the variable environment for the call to `Decorate` that the variable lives in is retained in memory as long as any function has a reference to that environment, and a function keeps a reference to the environment where it's created (and through it, all outer environments of that environment). The function is a *closure* over the environment containing `temp`. See the linked question and any decent JavaScript book or tutorial. (Or my ancient [blog post](http://blog.niftysnippets.org/2008/02/closures-are-not-complicated.html).) – T.J. Crowder May 19 '22 at 13:17

0 Answers0