The Illusion of Class
blog.javascriptroom.com
blog.javascriptroom.com
function Point(x, y){
if (!(this instanceof Point)) {
return new Point(x, y);
}
this.x = x;
this.y = y;
}
then you can just call: var point = Point(x, y);
HT to issacs (node, npm) who I picked that up from. 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. 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.
I think I'll be updating the article to include your modifications. Thanks (and how should I attribute? ef4 on HN?)
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)And keep in mind that this is a "classical" system tacked on top of a prototypal system. Not exactly elegant.
util.inherits(Point3d, Point);My solution: abstract away the headache. Use Underscore's extends function or take a look at how Prototype.js handles inheritance: http://prototypejs.org/learn/class-inheritance .
Both solutions are much more simple and do the same thing.
Also, if you are going into a JavaScript interview, know the stupid prototype pattern, someone always asks about it.
The Pseudo-Classical/Constructor pattern is the one that's broken.
function subclass(constructor, superConstructor)
{
function surrogateConstructor()
{
}
surrogateConstructor.prototype = superConstructor.prototype;
var prototypeObject = new surrogateConstructor();
prototypeObject.constructor = constructor;
constructor.prototype = prototypeObject;
}
Then you can say things like: subclass(DerivedConstructor, BaseConstructor);
There's a full write-up of this approach at http://www.golimojo.com/etc/js-subclass.html.One of the main benefits i found of using CoffeeScript's sugar for classical inheritance is that i no longer need to stop and think "ok, so am i doing things right here?" every time i inherit from a class or call a "super" method, which was the case when writing JS. It Just Works (TM).
Great article though! This is a constant source of confusion for anyone not intimately familiar with JavaScript.