Alan Kis
Alan Kis

Reputation: 1910

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.

Upvotes: 23

Views: 27058

Answers (4)

CodeToLife
CodeToLife

Reputation: 4141

very simplified approach:

class MyClass{
   static t
   constructor(){
      MyClass.t=this;
   }
   my1stMethod(){
      new SomeOtherClass( somevalue, function(){
        // now, here 'this' is a reference to SomeOtherClass so:
            MyClass.t.my2ndMethod();
    })
   }
 
   my2ndMethod(){
      console.log('im my2ndMethod');
      this.my3dMethod();
   }

   my3dMethod(){
      console.log('im my3dMethod');
   }
}

Upvotes: -3

Xitalogy
Xitalogy

Reputation: 1612

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.

Upvotes: 9

mor
mor

Reputation: 2313

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'

Upvotes: 2

romik
romik

Reputation: 520

You can try to get access to static property via constructor

console.log(myFoo.constructor.staticProperty);

Upvotes: 21

Related Questions