Here is code, I've been struggling for hours with that, idea is to keep track of how many instances is created, but also make possible to call static method and change/update static member. There is similar question, but I can't implement any solution to my problem.
// object constructor
function Foo() {
this.publicProperty = "This is public property";
}
// static property
Foo.staticProperty = "This is static property";
// static method
Foo.returnFooStaticProperty = function() {
return Foo.staticProperty;
};
console.log("Static member on class: " + Foo.staticProperty); // This is static property
console.log("Result of static method: " + Foo.returnFooStaticProperty()); //This is static property
var myFoo = new Foo();
console.log("myFoo static property is: " + myFoo.staticProperty); // undefined
For sake of simplicity I have changed constructor and member names here. I think it is obvious what happening. I want both of constructor object and instance share same static property.
I can access static member on constructor object, but on instance I got undefined.
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.
You can try to get access to static property via constructor
console.log(myFoo.constructor.staticProperty);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With