How to access static member on instance?
You can try to get access to static property via constructor
console.log(myFoo.constructor.staticProperty);
Javascript is prototype based. In other words, all instances of an object share the same prototype. You can then use this prototype to put static shared properties:
function Foo() {
this.publicProperty = "This is public property";
}
Foo.prototype.staticProperty = "This is static property";
var myFoo = new Foo();
console.log(myFoo.staticProperty); // 'This is static property'
Foo.prototype.staticProperty = "This has changed now";
console.log(myFoo.staticProperty); // 'This has changed now'
EDIT: I re-read your question, and this code solves your actual problem as stated:
JavaScript:
function Foo() {
this.publicProperty = "This is public property";
Object.getPrototypeOf(this).count++;
}
Foo.prototype.count = 0;
console.log(new Foo().count, new Foo().count, Foo.prototype.count);
This does not decrement the count automatically though if the object is freed up for garbage collection, but you could use delete then manually decrement.