That cannot be done.
JavaScript is object-oriented, and classes in JavaScript are just an illusion, created by setting an object's prototype property to a certain prototype object.
The new Foo() syntax is syntactic sugar for setting that prototype. And your best option, as others have shown, is to do the refCounting in the constructor function, effectively counting the amount of times that it got called. You can then store the count variable in the prototype or as a property of the constructor function itself or in an IIFE (see below), and return its value in the refCount function.
But if people start dynamically changing the object's prototypes, the objects can change class and I can think of no way for the refCount function to know that that happened.
var Foo
(function(){
var n = 0;
Foo = function Foo() {
this.refCount = Foo.refCount;
n++;
};
Foo.refCount = function() {
return n;
}
})()
function Bar() {}
f = new Foo();
console.log("created f, refCount = 1", f instanceof Foo, f.refCount(), Foo.refCount());
g = new Foo();
console.log("created g, refCount = 2", f instanceof Foo, g instanceof Foo, f.refCount(), g.refCount(), Foo.refCount());
g.__proto__ = Bar.prototype;
console.log("turned g into a Bar", f instanceof Foo, g instanceof Foo)
console.log("but refCount still is 2", Foo.refCount());
h = Object.assign(f)
console.log("created h without calling the constructor", h instanceof Foo)
console.log("But refCount still is 2", h.refCount(), Foo.refCount())
See it on JSBin
See https://developer.mozilla.org/en/docs/Web/JavaScript/Inheritance_and_the_prototype_chain and How to set the prototype of a JavaScript object that has already been instantiated?