- benefit: only one instance of each method created regardless of how many instances of the object are created
- downside: less clear about
this
bindings and under-the-hood ‘magic’ - benefit: act like Java people with ‘real’ classes, lolz
- under-the-hood:
- a new object is created and assigned to
this
this
is returned if nothing else is explicitly returned from the constructor- IF the constructor is invoked with the
new
keyword, then the constructor will delegate failed property lookups to the object at the .prototype property of the constructor
- a new object is created and assigned to
- lines 1 – 3: the constructor function
- line 2: assign whatever properties you want to the new instance, which has been auto-bound to
this
, and will be returned at the end of the constructor automagically
- line 2: assign whatever properties you want to the new instance, which has been auto-bound to
- lines 5 – 11: the method container object stored at the .prototype key of the constructor is being filled with methods
- these methods will be available to the new instance via failed property lookup delegation to the object at the .prototype key of the constructor function (if the instance was created with the
new
keyword)
- these methods will be available to the new instance via failed property lookup delegation to the object at the .prototype key of the constructor function (if the instance was created with the
We can now create as many Example
instances as we want, all with access to each method on the constructor’s prototype property, without having to store the methods themselves! It is as simple as var example = new Example();
.