EDIT: I figured it out from Bergi's answer in the end.
Thanks Bergi.
pubPrivExample = (function () {
return {
init : function () {
var private;
this.setPrivate = function (p) {
private = p;
};
this.getPrivate = function () {
return private;
};
},
public : "This is public\n"
};
}());
var a;
a = Object.create(pubPrivExample);
a.init();
a.setPrivate("This is private");
document.write(a.getPrivate());
EDIT: It seems the answers to my question are off at a tangent. I'm really not interested in a factory and actually would rather not use if. My question is about private state. From Bergi's answers and comments I think I can pull something together.
To be continued...
EDIT: Bergi has started to answer the question below, but left out the most important part - the private state.
I have had time to think about the idea more, but am still unable to achieve private state using Object.create() without some kind of factory. But I want to be wrong, and Bergi alluded to a solution... Feel free to take Bergi's answer as a starting point.
ORIGINAL: My quest to avoid new
in javascript has lead me to a peculiar place. I want private object members, but I don't want to give up Object.create()
.
Here's the code.
var trackQueue = {};
trackQueue.factory = function () {
var that, queue;
that = this;
queue = [];
that.push = function (item) {
queue.push(item);
};
that.work = function () {
document.write(queue + "<br />");
};
return {
work : that.work,
push : that.push
};
};
var a = Object.create( trackQueue.factory() );
a.push("a");
a.push("b");
a.push("c");
var b = Object.create( trackQueue.factory() );
b.push("d");
b.push("e");
b.push("f");
a.work();
b.work();
And a jsfiddle
http://jsfiddle.net/dsjbirch/Wj6cp/10/
Would init
be a more idiomatic / appropriate name for the factory
method?
Is this insane?
Be kind - javascript isn't my first language.