The new keyword in JavaScript can be quite confusing when it is first encountered, as people tend to think that JavaScript is not an object-oriented programming language.
- What is it?
- What problems does it solve?
- When is it appropriate and when not?
It does 5 things:
[[prototype]](i.e.__proto__) property to be the constructor function’s external, accessible,prototypeobject (every function object automatically has aprototypeproperty).thisvariable point to the newly created object.thisis mentioned.nullobject reference. In this case, that object reference is returned instead.Note: constructor function refers to the function after the
newkeyword, as inOnce this is done, if an undefined property of the new object is requested, the script will check the object’s
[[prototype]]object for the property instead. This is how you can get something similar to traditional class inheritance in JavaScript.The most difficult part about this is point number 2. Every object (including functions) has this internal property called
[[prototype]]. It can only be set at object creation time, either withnew, withObject.create, or based on the literal (functions default toFunction.prototype, numbers toNumber.prototype, etc.). It can only be read withObject.getPrototypeOf(someObject). There is no other way to get or set this value.Functions, in addition to the hidden
[[prototype]]property, also have a property called prototype, and it is this that you can access, and modify, to provide inherited properties and methods for the objects you make.Here is an example:
It’s like class inheritance because now, any objects you make using
new ObjMaker()will also appear to have inherited the ‘b’ property.If you want something like a subclass, then you do this:
I read a ton of rubbish on this subject before finally finding this page, where this is explained very well with nice diagrams.