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
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
newby 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);
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.