5

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

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

3 Comments

Hmm. complicated, but works. As the "var enterscope" is specific to M, it could be then changed to: M.scoped = function(func) { var m=new M; func(m); m.destruct(); }; and then the use of it would be: M.scoped(function(m) { m.inc(); m.inc(); });
Sorry, should have written: var enterscope-definition could be made specific to M...
item.destruct() should be wrapped in the finally block: try { func(item); } finally { item.destruct(); }
1

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".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.