类似于基于stackbased对象在c ++的javascript [英] something like stackbased objects in c++ for javascript

查看:109
本文介绍了类似于基于stackbased对象在c ++的javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在javascript中寻找一个构造,它的工作方式类似于stackbased中的析构函数或c ++中的局部对象,例如

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");

所以这意味着我正在寻找一个结构, 超出范围)。它应该是鲁棒的,它不需要在范围的结束时的特殊操作,就像c ++中的析构函数(用于包装mutex-alloc和释放)。

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

干杯,mg

推荐答案

保证是同步的,你可以创建一个函数来调用析构函数。它可能不是那么灵活,并且语法可能不像C ++那样整洁,但是:

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();
};

您可以使用它如下:

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

这将被记录:

created
inc
inc
destructed 2

这篇关于类似于基于stackbased对象在c ++的javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆