something like stackbased objects in c++ for javascript

自作多情 提交于 2019-12-05 09:15:01

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

Sadly you won't be able to find what you are looking for since the language design doesn't force the implementation of the ECMAScript engine (ie. the javascipt interpreter) to do what your require.

The garbage-collector will (actually it's more of a "might") kick in when there are no more references to the object going out of scope, but there isn't any standardised way of you (as the developer) to take advantage of this.

There are hacks (such as wrapping the usage of your object in a function taking the object itself and a "usage"-callback function) to provide functionality similar to dtor's in C++, but not without taking any "extra action".

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!