I\'ve been instantiating subclasses in javascript using
object = new class ()
but I notice some people instantiate using
ob
The difference is that when you do:
var subclass = new superclass();
you are creating an instance of superclass
. subclass
is just variable. You are not creating a sub-class (ie. making subclass
inherit superclass
).
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:
function superclass() {this.stuff="stuff";}
function subclass() {}
subclass.prototype = new superclass();
alert(new subclass().this); // pops up "stuff"
is prototypical inheritance.
As for the new
operator, 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 superclass
type/function itself.