How to access a static member on an instance?

Hi stackers.

Here is the code, I have been struggling with this for hours, the idea is to keep track of how many instances are created, but it also allows you to call the static method and change / update the static member. There is a similar question, but I cannot 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 simplicity, I have changed the names of the constructors and members here. I think it is obvious what is happening. I want both the constructor object and the instance to have the same static property.

I can access the static member on the constructor object, but for example, I got undefined.

Any help would be appreciated.

Thanks to both mor and aeoril. Due to the fact that this question has been localized, the answer from you will help me better understand prototype inheritance. Postscript In Javascript there is no such thing as a static member, an instance of the object does not directly inherit it, as I expected. So here comes the prototype of magic. Thanks

+7
javascript oop static-methods static-members
source share
3 answers

EDIT: I will re-read your question and this code solves your actual problem as indicated:

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); 

Fiddle

This does not automatically reduce the count, but if the object is freed for garbage collection, but you can use delete and then manually reduce it.

+6
source share

You can try to access the static property through the constructor

 console.log(myFoo.constructor.staticProperty); 
+5
source share

Javascript is prototype based. In other words, all instances of the object have the same prototype. Then you can use this prototype for static common 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' 
+2
source share

All Articles