You can't. In order to do what you describe, you'd have to be able to receive a callback from the JavaScript engine when an object is about to be garbage-collected or when the last reference to it is released. There is no such callback.
Your best bet: Look at the larger picture of your design, to find a way not to need to do this. The new ES2015 WeakMap and/or WeakSet objects may be useful in that greater design.
Very much a distant second-best alternative: If you can require that users of your object call a method, for instance destroy, when they think they're done referencing the object, you could do it, but that would be very prone to failure because of usage errors (failing to call destroy).
Here's that very prone-to-failure example:
var CountedThing = (function() {
var instances = 0;
function CountedThing() {
if (!this.hasOwnProperty("destroyed")) {
++instances;
this.destroyed = false;
if (instances === 1) {
// First instance created
}
}
}
CountedThing.prototype.destroy = function() {
if (!this.destroyed) {
this.destroyed = true;
--instances;
if (instances === 0) {
// Last instance "destroyed"
}
}
}
return CountedThing;
})();
But again, that's very prone to failure. It can work (look at any well-written C program, which has to manage its memory in a similear way), but doing it properly is tricky (look at the millions of memory-related bugs in C programs).