I am trying to make a class (called Foo
) like object in JavaScript that would let me create multiple instances of Foo
. By multiple instances, I mean, each instance would maintain separate internal state. This is how I am achieving it.
var Foo = function() {
function init(a) {
this.a = a
}
function state() {
return this.a
}
function getFoo() {
return {
init: init,
state: state
}
}
return {
getFoo: getFoo
}
}()
var a = Foo.getFoo()
var b = Foo.getFoo()
a.init(10)
b.init(20)
alert(a.state() + ', ' + b.state())
As you can see that the Foo.getFoo()
seems to simulate the Factory pattern usually used in Java. The internal state is the variable this.a
. I consider my attempt a success because a.state()
and b.state()
display two different internal states. However, this is purely my attempt without any knowledge of how these things are implemented in the industry.
Now, my questions may seem like a request for code review and is at the risk of getting closed, so I will try to make my questions as objective as possible.
- How can the same code be implemented such that
new
operator can be used instead to create the new instances of a class withthis.a
as the internal state? - How is my code with the factory pattern written in the industry?