I’ve been instantiating subclasses in javascript using
object = new class ()
but I notice some people instantiate using
object.prototype = new class ()
Question: What’s the difference? To me it seems like the latter is respecting the inheritance chain more because if class () has a bunch of “this.variable = x” statements, and object is something you want to inherit from it rather than an instance of class, you are accurately assigning those variables to object’s prototype rather than to the object itself as in the former case. So in effect it’s like this?
object = new class () |vs.| subclass.prototype = new superclass ()
However, functionally in the program both are the same?
Side question: Also I’m a bit unclear as to what the new operator actually does. It seems to me to do something like just create an empty object and assign it’s proto property?
The difference is that when you do:
you are creating an instance of
superclass.subclassis just variable. You are not creating a sub-class (ie. makingsubclassinheritsuperclass).In the latter example, assuming subclass is a function, you are saying that all new instances of subclass should inherit (ie. sub-class)
superclass.So:
is prototypical inheritance.
As for the
newoperator, it is used for creating an instance of built-in objects and user defined types. A user defined type is simply a function.Edit:
When I wrote above that subclass inherits supertype using prototypical inheritance, I mean that all new instances of subclass inherit from one particular instance of superclass, not from the
superclasstype/function itself.