user3508264 user3508264 - 2 months ago 8
Javascript Question

How to create a private static variable in prototype pattern

In the code below, all instaniated Page objects get their Id from the static variable 'nextId'. What is the best way to reset nextId? I don't like the way I'm doing it because it's accessed through an instantiated object. I'd rather do something like:

Page.reset(). How is it possible?

https://plnkr.co/edit/heOz52QxK6CExhe8Hdfm?p=preview

var Page = (function() {

var nextId = 0;

function Page(content) {
this.id = nextId++;
this.content = content;
}

Page.prototype.reset = function() {
nextId = 0;
}

Page.prototype.show = function() {
console.log(this.content + ' is ' + this.id);
}

return Page;



}())


var a = new Page('a')
a.show() // a is 0

var b = new Page('b')
b.show() // b is 1

var c = new Page('c')
c.show() // c is 2

a.reset()

var d = new Page('d')
d.show() // d is 0

Answer

Define #reset() on the Page object, rather than on it's prototype:

Page.reset = function() {
  nextId = 0;
}
Comments