4 ms·
That is an excellent point. I mean, ideally the constructor doesn't have side effects, but this is a good defense against those that do.
by ryankinal 14y ago
That is an excellent point. I mean, ideally the constructor doesn't have side effects, but this is a good defense against those that do.
- ef4 14y agoEven side-effect free constructors can make this pattern painful. Consider the case where we're trying to maintain the invariant that all Points always have valid numbers for all their coordinates: var Point = function(x, y) { if (typeof(x)!='number' || typeof(y)!='number'){ throw new Error("..."); } this.x = x; this.y = y; } Now you're forced to pick an arbitrary point when setting up the prototype, which is kinda gross. My point is that people write constructors with the expectation that they'll only be used for constructing meaningful objects.