Skip to content
Advertisement

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?

Advertisement

Answer

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)

In simple words this refers to the context of the current object instance, whereas static property refers to the prototype. Static properties are not directly accessible by this keyword. To access them you need to use its prototype name. Like here in the above code foo.<your_property_name>. Even static methods are called in the same way foo.<your_method_name>().


You can get the basic difference of both with Object.getOwnPropertyNames() for instance and its prototype(will avoid using an object to point factory function to void confusion). The instance has its own property referring to the current object context, whereas the prototype has its own set of properties.

function foo(){
  this.count = 1;
  foo.myOwnCount = 1;
}
const a = new foo();
const b = new foo();
console.log(Object.getOwnPropertyNames(a));
console.log(Object.getOwnPropertyNames(foo));

You can see instance have access to count property which can be accessed with this keyword but not to myOwnCount. And prototype has access to myOwnCount (which can be accessed with the prototype name), but not count.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement