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