Can someone help me understand how to extend classes in JavaScript?
Here's a slightly altered CoffeeScript extends function. Typescript's is similar.
var extend = function(child, parent) { for (var key in parent) { if (parent.hasOwnProperty.(key)) { child[key] = parent[key]; } }
function Ctor() { this.constructor = child; }
Ctor.prototype = parent.prototype; child.prototype = new Ctor(); child.super = parent.prototype;
return child; };
In the first part of the function, I don't fully understand the reasoning behind copying all of the properties of the parent object to the child. In normal prototypal inheritance you would do Child.prototype = new Parent('arg1'). This would set the prototype of the Child constructor function to an instance of the Parent object. When instances of Child are created, they can look up in the prototype chain and have access to variables and functions of a Parent object. This is in contrast to conventional inheritance, where specifying that you want one class to extend another class means that the child class is the parent class with added on functions and variables.
By copying all of the direct properties of the parent onto the child you have variables that are unique for each child object instance. Am I thinking about this correctly?
If you look at the inheritance part of http://coffeescript.org/, you see the uglified code above. One thing I noticed is that
for (var key in parent) { if (parent.hasOwnProperty.(key)) { child[key] = parent[key]; } }
Is actually not even run for the example they have set up. Does anyone know the scenario in which this is run?
function Ctor() { this.constructor = child; }
This part is where I get really confused. In this case, is constructor an overloaded variable name? What is it's relationship with the regular Javascript-reserved constructor variable?
Ctor.prototype = parent.prototype;
Setting a new constructor function's prototype to be equal to the parent's prototype. Hm. I'm kind of unclear about this. This would make the parent's prototype a new constructor function's prototype. So it would inherit all the parent's prototype's properties, which are usually functions. This seems to make sense from a classical perspective, in that a parent's functions are inherited.
child.prototype = new Ctor();
Make the child function's prototype equal to the constructor function we were talking about before. I'm lost.
child.super = parent.prototype;
Make a new property for child, super, which represents the parent class. Set its value to the prototype of the parent. This means that when you use .super in the future, you are able to access the parent's functions. Seems to make sense.. I guess.
This is kind of confusing. Is someone able to explain what is going on and compare it to classical inheritance?
Posted Apr 13, 2015, 8:53 PM UTC
First as some background: calling a function with
newin JavaScript kicks off a two-part process: first, allocation, then, initialization. Allocation is implicit -- it creates a new object and sets that object's prototype to the prototype property of the constructor, but you don't need to worry about any of this (except of course making sure to usenew). Initialization is mostly explicit: (i.e. the code in the body of the constructor function is executed), but has two caveats: first, thethisvalue is set to the newly-created object, and second, if nothing is explicitly returned by the constructor, the newly-created object is returned.Second: the business with CoffeeScript creating the throwaway
Ctorconstructor for every extension is so that it's compiled JavaScript will work in pre-ES5 environments. TheObject.createmethod was added to JavaScript specifically to allow objects to be created with a specific prototype. Modern inheritance implementations tend to useObject.create. For an example, see Node's inherit util.Moving on to:
for (var key in parent) { if (parent.hasOwnProperty.(key)) { child[key] = parent[key]; } }The line above simply copies properties of the parent constructor onto the child constructor. In classical terms, these tend to be 'static methods' (although they could be simple properties rather than functions).
Since inheritance is through prototype, there's no built-in method for inheriting static methods. (I think this will be different in ES6, where subtyping does actually establish a prototype chain between constructors, not just their associated prototypes.)
As far as the use of
supergoes, it's not strictly necessary. Check out the CoffeeScript code here and the JS translation. The body of theOtherThingconstructor readsreturn OtherThing.__super__.constructor.apply(this, arguments);However,
Thingis in scope here under the namesuperClass. Thus, the above line could also be writtensuperClass.apply(this, arguments);Calling the super class constructor is something you don't mention in your question, however it is generally important to run the super constructor's initialization step of instantiation when creating an instance of a subtype.
Thanks for the detailed response.
I didn't know what I was talking about in regards to the loop copying over static properties of the constructor function.
In regards to the pre-ES5 object creation mechanism, I found what I assume to be the rough implementation of Object.Create as described here
Object.create = function (o) { function F() {} F.prototype = o; return new F(); };Which looks similar to Ctor. I still don't really get what's going on here.
I noticed child.prototype = new Parent() isn't used anywhere. Don't you want to do this so that you can get a copy of all the properties of the Parent class? I don't get what
this.constructor = childmeans. Isn't this.constructor Ctor itself?Edit: Wait a minute. Doing
Ctor.prototype = parent.prototypethen usingchild.prototype = new Ctor()would do accomplish that, but without the constructor function variables, just the prototype variables. Using__super__.constructor.apply(this, arguments);would call parent.prototype.constructor which is the parent constructor function itself, thereby getting the constructor function (per instance) variables.So I don't quite get why it's being done this way, but it's something. So I think understand everything now except for
function Ctor() { this.constructor = child; }.You get something similar to
child.prototype = new Parent()when you do that loop and:Just going through
Ctorin the middle. As u/curvebottle said, you getParent's "static" or own properties in the loop. Then you: a. pointCtor.prototypetoparent.prototypeand, b. putting anew Ctoraschild.prototypeyou getCtor's prototype (which, remember, isparent.prototype) to bechild's prototype.This is mostly what you'd get by doing it directly, but with a level of indirection through
Ctor, precisely so you can put there those "static"/own properties of theParent.You can ignore
this.constructor = childfor the purpose of understanding all this. It's only done for "identification purposes", that is, it's only done so that when you create achildobject, it's constructor property correctly points tochild. You don't want to do avar bob = new Child()and havebob.constructorread as something weird likeCtor.How does using Ctor enable to copy the parent's (static) properties to the child? If you don't go past the loop, it already seems to do this (without Ctor being used at all).
No, no... Maybe I didn't express it to precisely: You copy those properties directly form parent to child in the loop. You use
Ctorto set up the prototypes.