something like stackbased objects in c++ for javascript

◇◆丶佛笑我妖孽 提交于 2019-12-07 05:53:59

问题


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


回答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



回答2:


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



来源:https://stackoverflow.com/questions/13218199/something-like-stackbased-objects-in-c-for-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!