Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Accessing a common property in a factory function

Say I want to have a counter in a factory function that counts the number of objects that were made, I can do it as such:

function foo(){
    // Factory code
    this.counter = this.counter? this.counter + 1 : 1
    console.log(this.counter)
}

let a = foo(); // Logs 1 
let b = foo(); // Logs 2,
console.log(foo.counter) // undefined

What this shows, is that the counter property is being saved and edited on the foo function object. But foo.counter is undefined. So my question is:

Where is the property being saved and how can I access it?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can add a static property to count

function foo(){
    // Factory code
    foo.counter = foo.counter? foo.counter + 1 : 1;
    console.log(foo.counter)
}

let a = foo();
let b = foo();
console.log(foo.counter)

static property to count.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading