2012-11-04 38 views
5

尋找一個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)。

乾杯,毫克

回答

1

如果範圍代碼保證是同步的,你可以創建之後調用析構函數。它可能不是那麼靈活和語法可能不會像C作爲整齊++,雖然:

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

這將被記錄:

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

你可以按如下方式使用它

created 
inc 
inc 
destructed 2 
+2

嗯。複雜,但有效。由於「var輸入範圍」特定於M,因此可以將其改爲: M.scoped = function(func)var m = new M; func(m); m.destruct(); }; (); 然後它的使用將是: M.scoped(function(m){0;}; m.inc(); }); – MGrant

+0

對不起,應該寫成:var entercope-definition可以製作成特定於M ... – MGrant

+1

'item.destruct()'應該包裝在'finally'塊中: 'try {func(item); } finally {item.destruct(); }' – user

1

不幸的是,你將無法找到你要找的東西,因爲語言設計不會強制執行ECMAScript引擎(即javascipt解釋器)來執行你的要求。

垃圾回收器(實際上它更像是一個「might」),當沒有更多引用超出範圍的對象時,但沒有任何標準化的方法(如開發人員)利用這一點。

有一些竅門(比如將對象用在對象本身和「usage」回調函數中)來提供類似於C++中的dtor的功能,但並非沒有采取任何「額外行動」。