2 months later
Maybe you need a library, ES5 is verbose, so I created pd
Original answer
I am looking for an OOP solution / library for Node.js.
You do not need a library. You have ES5 .
JavaScript does not have classic OOP. He prototypes OOP.
This means that you only have objects. The only things you can do with objects are expansion, manipulation, and cloning.
Manipulation
var o = {}; o.foo = "bar";
Extend
var o = someObject; Object.defineProperties(o, { "foo": { value: "foo" }, "bar": { value: "bar" } "method": { value: function () { } } }
Clone
var o = someObject; var p = Object.create(o);
Clone and extension
var o = someObject; var p = Object.create(o, { "foo": { value: "foo" }, "bar": { value: "bar" } "method": { value: function () { } } }
It is important to understand how Object.create , Object.defineProperty and Object.defineProperties .
The cloning operation is not actually cloned. This creates a new object from the plan. A project is an object. It places the project in [[Prototype]] . [[Prototype]] lives in the .__proto__ , which I will use for demonstration.
var o = {}; var p = Object.create(o); p.__proto__ === o; // true var q = Object.create(p); q.__proto__.__proto__ === o; var r = Object.create(q); r.__proto__.__proto__.__proto__ === o;
Disclaimer: .__proto__ out of date. Do not use it in code. It uses it to verify debugging and to verify health.
The main thing is that access to properties from o to r must go three levels up the prototype chain, and this becomes expensive. To solve this problem, and not clone random objects, you must clone specific drawings (and you must have one project for each object).
// Parent blueprint var Parent = (function _Parent() { // create blank object var self = Object.create({}); // object logic return self; }()); // factory function var createParent = function _createParent(foo) { // create a object with a Parent prototype return Object.create(Parent, { foo: { value: foo } }); } var Child = (function _Child() { var self = Object.create(Parent); // other stuff return self; }()); var createChild = function _createChild(bar) { return Object.create(Child, { bar: { value: bar } }) };
Here's a snippet of code I'm working on that can be used as an example:
var Sketchpad = (function _SketchPad() { var self = Object.create({}); var mousemove = function _mousemove(e) { this.drawLine(e); }; self._init = function _init() { this.$elem.bind({ "mousemove": mousemove.bind(this), }); this.pens = {}; $("#clear").bind("click", this.clear.bind(this)); $("#undo").bind("click", (function _undoPath() { this.pen.undo(); }).bind(this)); return this; }; self.clear = function() { this.paper.clear(); }; return self; }()); createSketch = function _createSketchPad(id, w, h) { var paper = Raphael(id, w, h); var pen = createPen(paper); var o = Object.create(Sketchpad, { paper: { value: paper }, $elem: { value: $("#" + id) }, pen: { get: function() { return pen; }, set: function(v) { pen = v; } } }); return o._init(); };