Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access static member on instance?

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.

like image 397
Alan Kis Avatar asked Oct 19 '13 20:10

Alan Kis


2 Answers

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.

like image 151
Xitalogy Avatar answered Sep 28 '22 05:09

Xitalogy


You can try to get access to static property via constructor

console.log(myFoo.constructor.staticProperty);
like image 24
romik Avatar answered Sep 28 '22 05:09

romik