Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

something like stackbased objects in c++ for javascript

Looking for a construct in javascript which works like the destructor in stackbased or local object in c++, e.g.

#include <stdio.h>
class M {
public:
  int cnt;
  M()        {cnt=0;}
  void inc() {cnt++;}
  ~M()       {printf ("Count is %d\n", cnt);}
};
...
{M m;
 ...
 m.inc ();
 ...
 m.inc ();
} // here the destructor of m will printf "Count is 2");

so this means I am looking for a construct which does an action when its scope is ending (when it "goes out of scope"). It should be robust in the way that it does not need special action at end of scope, like that destructor in c++ does (used for wrapping mutex-alloc and release).

Cheers, mg

like image 226
MGrant Avatar asked Nov 04 '22 12:11

MGrant


2 Answers

If the code in the scope is guaranteed to be synchronous, you can create a function that calls the destructor afterwards. It may not be as flexible and the syntax may not be as neat as in C++, though:

var M = function() {
  console.log("created");
  this.c = 0;
};

M.prototype.inc = function() {
  console.log("inc");
  this.c++;
};

M.prototype.destruct = function() {
  console.log("destructed", this.c);
};


var enterScope = function(item, func) {
  func(item);
  item.destruct();
};

You could use it as follows:

enterScope(new M, function(m) {
  m.inc();
  m.inc();
});

This will be logged:

created
inc
inc
destructed 2
like image 124
pimvdb Avatar answered Nov 09 '22 15:11

pimvdb


Sadly you won't be able to find what you are looking for since the language design doesn't force the implementation of the ECMAScript engine (ie. the javascipt interpreter) to do what your require.

The garbage-collector will (actually it's more of a "might") kick in when there are no more references to the object going out of scope, but there isn't any standardised way of you (as the developer) to take advantage of this.

There are hacks (such as wrapping the usage of your object in a function taking the object itself and a "usage"-callback function) to provide functionality similar to dtor's in C++, but not without taking any "extra action".

like image 41
Filip Roséen - refp Avatar answered Nov 09 '22 16:11

Filip Roséen - refp