4 ms·
Don't use Point3d.prototype = new Point(); if the constructor has side effects. Instead, function fn(){}; fn.prototype = Point.prototype; Point3d.prototy
by quarterto 14y ago
Don't use
Point3d.prototype = new Point();
if the constructor has side effects. Instead,
function fn(){}; fn.prototype = Point.prototype; Point3d.prototype = new fn;
does what you want.
- ryankinal 14y agoThat 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.
- masklinn 14y agoAlternatively, if you're only supporting modern-ish browsers, Point3d.prototype = Object.create(Point.prototype); which does the same thing but does not require multiple statements (and allows adding property definitions as the second argument)
- camus 14y agoand some sell javascript as simple and well designed...
- ryankinal 14y agoSimple, sure. Well-designed? Nah. And keep in mind that this is a "classical" system tacked on top of a prototypal system. Not exactly elegant.
- dclowd9901 14y agoI don't think I've ever heard even the staunchest JavaScript writers refer to it as "well-designed".
- greggman 14y agovs? every language has worts
- baudehlo 14y agoOr if you're using Node, it's just: util.inherits(Point3d, Point);