Something like stack based objects in C ++ for javascript

Looking for a construct in javascript that works like a destructor on a stack 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"); 

therefore, this means that I am looking for a construct that performs an action when its scope ends (when it "goes out of scope"). It should be reliable in the sense that it does not need special actions at the end of the scope, as the destructor does in C ++ (used to wrap mutex-alloc and release).

Greetings, mg

+5
c ++ javascript scope destructor
Nov 04 '12 at 11:41
source share
2 answers

If the code in the area is guaranteed to be synchronous, you can create a function that subsequently calls the destructor. This may not be as flexible, and the syntax may not be as neat as in C ++, but:

 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 can use it as follows:

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

This will be recorded:

 created inc inc destructed 2 
+1
Nov 04
source share

Unfortunately, you cannot find what you are looking for, because the design of the language does not force the implementation of the ECMAScript mechanism (i.e. the javascipt interpreter) to do what you need.

Garbage collector (in fact, it’s more likely β€œcan”) when there are no more references to an object that goes out of scope, but there is no standardized way (as a developer) use this.

There are hacks (for example, wrapping the use of your object in a function that takes the object itself, and the "use" callback function) to provide functionality similar to dtor in C ++, but not without any additional actions. "

+1
Nov 04
source share



All Articles