I'm trying to wrap my head around this pattern, because it is unlike anything I've come across in the past.
Me neither. It doesn't do much magic, but he structure is definitely uncommon. See Correct javascript inheritance for the right pattern.
Can somebody explain to me why you would want to use an instance of a class as a new class' prototype?
You don't. You want to use an object that inherits from the parent class's prototype object. Unfortunately many people use new ParConstructor
for that - which works well if the constructor function is empty. If the constructor does create instance properties or has other side effects, it can cause trouble. Most people don't seem to notice or care about that, though.
explanation of this pattern?
function Ship() {
this.initialize();
}
This just calls the initialize
method on the new instance (this
in a constructor). I don't see any benefits over placing the initialisation code directly in the constructor, but be that as it may.
var p = Ship.prototype = new createjs.Container();
As explained above, this is setting up the prototype chain to inherit methods from the Container
"class". It probably does unnecessary instance initialisation, so it should be replaced with an Object.create
call. And it creates a shortcut variable to the prototype.
// constructor:
p.Container_initialize = p.initialize; //unique to avoid overiding base class
Here, an explicit reference to the parent's constructor is created. The initialize
property on p
is inherited from the Container
prototype, and now it is made an own property of the p
object with a descriptive name. That is needed because …
p.initialize = function () {
this.Container_initialize();
… // property init stuff
… here an own initialize
method is declared on the prototype object, shadowing the inherited one. Still, the "super" initialisation code can now be invoked on the current instance using that dedicated property. Doing that is quite common, but not in this way with the method. Instead, call
is normally used to apply the parent constructor on the child instance.
Better (at least, more familiar):
function Ship() {
this.initialize();
}
var super_p = createjs.Container.prototype,
p = Ship.prototype = Object.create(super_p);
p.initialize = function() {
super_p.initialize.call(this);
… // property init stuff
Or, alternatively without initialize
:
function Ship() {
createjs.Container.call(this);
… // property init stuff
}
Ship.prototype = Object.create(createjs.Container.prototype);