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
.