类似于c ++中用于javascript的基于堆栈的对象

MGr*_*ant 5 javascript c++ destructor scope stack-based

在javascript中寻找一个构造,就像在c ++中的stackbased或local对象中的析构函数一样,例如

#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");
Run Code Online (Sandbox Code Playgroud)

所以这意味着我正在寻找一个构造,当它的范围结束时(当它"超出范围"时)执行一个动作.它应该是健壮的,因为它不需要在范围结束时采取特殊操作,就像c ++中的析构函数那样(用于包装mutex-alloc和release).

干杯,毫克

pim*_*vdb 1

如果保证作用域中的代码是同步的,您可以创建一个随后调用析构函数的函数。但它可能不像 C++ 那样灵活,语法也可能不像 C++ 那样简洁:

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();
};
Run Code Online (Sandbox Code Playgroud)

您可以按如下方式使用它:

enterScope(new M, function(m) {
  m.inc();
  m.inc();
});
Run Code Online (Sandbox Code Playgroud)

这将被记录:

created
inc
inc
destructed 2
Run Code Online (Sandbox Code Playgroud)

  • 唔。复杂,但有效。由于“var Enterscope”特定于 M,因此可以将其更改为: M.scoped = function(func) { var m=new M; 函数(米);m.destruct(); }; 然后它的用法是: M.scoped(function(m) { m.inc(); m.inc(); }); (2认同)