user6317504 user6317504 - 6 months ago 13
Javascript Question

Code Challenge: Create a class Foo that tracks the number of total object instances

I am trying to solve a code challenge for a job app, but I am stuck and would appreciate any help.

Question: Create a class Foo that has a method called refCount. Calling refCount on the class or any of its instances should return how many total instances exists.

Example:

var f1 = new Foo();

f1.refCount(); // should be 1
Foo.refCount(); // should be 1

var f2 = new Foo();

f1.refCount(); //should be 2
f2.refCount(); // should be 2
Foo.refCount(); // should be 2


I have something like this so far:

function Foo() {

this.refCount = function() {
++Foo.prototype.refs;
return Foo.prototype.refs;
}

}

Foo.prototype.refs = 0;


I also tried using an IIFE to attach a method to the class itself, but then I was unable to figure out how to create new instances.

Answer
function Foo() {
    Foo.__n++;
}
Foo.refCount = function() { return Foo.__n; }
Foo.__n = 0;
Foo.prototype.refCount = Foo.refCount;

Output:

> var f = new Foo(); console.log(f.refCount(), Foo.refCount());
1 1
> f = new Foo(); console.log(f.refCount(), Foo.refCount());
2 2
> f = new Foo(); console.log(f.refCount(), Foo.refCount());
3 3