I tweeted recently about new
operator: ‘if your JS library API expecting me to write “new” — you’re doing it wrong.’ Let me clarify it a bit.
I am not saying that using new
operator is a bad idea, it’s an essential operator, but asking me to use it with your API is a bad idea. Lets look at box2d.js API for example. Because it was supposed to copy C++ API, it took all C-like decisions and copied it straight to JavaScript. It’s ok for something that was ported, but I see the same patterns in APIs created in JavaScript from the scratch.
Example:
var m_world = new b2World(new b2Vec2(0.0, -9.81), true);
I would say it should look something like this instead:
var m_world = box.world(0.0, -9.81);
Why is it better?
- Saves characters to type, makes code less verbose
- If you put
new
by mistake… nothing will happen - User shouldn’t care if your function returns object literal or instance of some “class”
I will illustrate last point on Raphaël code. Lets say you want to create a circle and you want to take it bounding box and log x and width of it:
var c = paper.circle(x, y, r),
bb = c.getBBox();
console.log(bb.x, bb.width);
With new
approach I should write it like this:
var c = new paper.Circle(x, y, r),
bb = new BBox(c); // global? may be Raphael.BBox()?
console.log(bb.x, bb.width);
I found last one to be harder to read, error-causing and generically not nice.