I generally write my constructor functions so I can easily forget 'new':<p><pre><code> function Point(x, y){
if (!(this instanceof Point)) {
return new Point(x, y);
}
this.x = x;
this.y = y;
}
</code></pre>
then you can just call:<p><pre><code> var point = Point(x, y);
</code></pre>
HT to issacs (node, npm) who I picked that up from.
Don't use<p><pre><code> Point3d.prototype = new Point();
</code></pre>
if the constructor has side effects. Instead,<p><pre><code> function fn(){}; fn.prototype = Point.prototype; Point3d.prototype = new fn;
</code></pre>
does what you want.
The JavaScript prototype pattern is the most poorly designed aspect of the JavaScript language. Cross-browser prototype compatibility is a total headache too.<p>My solution: abstract away the headache. Use Underscore's extends function or take a look at how Prototype.js handles inheritance: <a href="http://prototypejs.org/learn/class-inheritance" rel="nofollow">http://prototypejs.org/learn/class-inheritance</a> .<p>Both solutions are much more simple and do the same thing.<p>Also, if you are going into a JavaScript interview, know the stupid prototype pattern, someone always asks about it.
Whenever I find myself needing to roll my own class-based system in JavaScript I use this function:<p><pre><code> function subclass(constructor, superConstructor)
{
function surrogateConstructor()
{
}
surrogateConstructor.prototype = superConstructor.prototype;
var prototypeObject = new surrogateConstructor();
prototypeObject.constructor = constructor;
constructor.prototype = prototypeObject;
}
</code></pre>
Then you can say things like:<p><pre><code> subclass(DerivedConstructor, BaseConstructor);
</code></pre>
There's a full write-up of this approach at <a href="http://www.golimojo.com/etc/js-subclass.html" rel="nofollow">http://www.golimojo.com/etc/js-subclass.html</a>.
Question: in the object tree for Point3d, it looks like there are two __proto__ attributes at the same level of nesting. Should the second belong to Point and be indented? (I'm not that experienced with javascript so I could simply be confused.)
Can't help but picture GOB Bluth: "Illuuuusions, Michael!"<p>Great article though! This is a constant source of confusion for anyone not intimately familiar with JavaScript.