尋找一個JavaScript中的構造,其工作方式類似於C++中基於堆棧或局部對象的析構函數。類似javascript中的基於堆棧的對象
#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和release)。
乾杯,毫克
嗯。複雜,但有效。由於「var輸入範圍」特定於M,因此可以將其改爲: M.scoped = function(func)var m = new M; func(m); m.destruct(); }; (); 然後它的使用將是: M.scoped(function(m){0;}; m.inc(); }); – MGrant
對不起,應該寫成:var entercope-definition可以製作成特定於M ... – MGrant
'item.destruct()'應該包裝在'finally'塊中: 'try {func(item); } finally {item.destruct(); }' – user