如何计算对象的实例? [英] How can I count the instances of an object?

查看:77
本文介绍了如何计算对象的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我将Javascript对象定义为:

If i have a Javascript object defined as:

function MyObj(){};

MyObj.prototype.showAlert = function(){
   alert("This is an alert");
   return;
};

现在用户可以将其称为:

Now a user can call it as:

var a = new MyObj();
a.showAlert();

到目前为止一直很好,也可以在同一个代码中运行另一个这样的实例:

So far so good, and one can also in the same code run another instance of this:

var b = new MyObj();
b.showAlert();

现在我想知道,我怎么能保持MyObj实例的数量?
是否有一些内置函数?

Now I want to know, how can I hold the number of instances MyObj? is there some built-in function?

我想到的一种方法是在MyObj初始化时增加一个全局变量,这将是唯一的跟踪这个计数器的方法,但有什么比这个想法更好吗?

One way i have in my mind is to increment a global variable when MyObj is initialized and that will be the only way to keep track of this counter, but is there anything better than this idea?

编辑:

在这里看一下这个建议:

Have a look at this as suggestion here:

我的意思是我怎么能让它回到2而不是3

I mean how can I make it get back to 2 instead of 3

推荐答案

内置任何东西;但是,你可以让你的构造函数保持计数它被调用的次数。遗憾的是,JavaScript语言无法判断对象何时超出范围或已被垃圾回收,因此您的计数器只会上升,永不停机。

There is nothing built-in; however, you could have your constructor function keep a count of how many times it has been called. Unfortunately, the JavaScript language provides no way to tell when an object has gone out of scope or has been garbage collected, so your counter will only go up, never down.

例如:

function MyObj() {
  MyObj.numInstances = (MyObj.numInstances || 0) + 1;
}
new MyObj();
new MyObj();
MyObj.numInstances; // => 2

当然,如果你想防止篡改计数,你应该通过一个隐藏计数器关闭并提供一个访问函数来阅读它。

Of course, if you want to prevent tampering of the count then you should hide the counter via a closure and provide an accessor function to read it.

根据您更新的问题 - 无法跟踪实例何时不再使用或删除(例如,通过为变量赋值null),因为JavaScript不提供终结器方法

Per your updated question - there is no way to keep track of when instances are no longer used or "deleted" (for example by assigning null to a variable) because JavaScript provides no finalizer methods for objects.

你能做的最好的事情就是创建一个dispose方法当他们不再活跃时会打电话(例如通过引用计数计划),但这需要合作程序员 - 该语言不提供帮助:

The best you could do is create a "dispose" method which objects will call when they are no longer active (e.g. by a reference counting scheme) but this requires cooperation of the programmer - the language provides no assistance:

function MyObj() {
  MyObj.numInstances = (MyObj.numInstances || 0) + 1;
}
MyObj.prototype.dispose = function() {
  return MyObj.numInstances -= 1;
};
MyObj.numInstances; // => 0
var a = new MyObj();
MyObj.numInstances; // => 1
var b = new MyObj();
MyObj.numInstances; // => 2
a.dispose(); // 1 OK: lower the count.
a = null;
MyObj.numInstances; // => 1
b = null; // ERR: didn't call "dispose"!
MyObj.numInstances; // => 1

这篇关于如何计算对象的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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