Class
“Instantiating” a class in JavaScript does create a new object, but not one that is independent of its parent class. Rather, it creates an object that is linked to a prototype. Changes to that prototype propagate to the new object, even after instantiation.
Classes can only contain method definitions, not data properties;
A derived class can’t contain an empty constructor. Even if all the constructor does is call super(), you’ll still have to do so explicitly. It can, however, contain no constructor.
You must call super in the constructor of a derived class before you use this.
Calling any function with the new keyword causes it to return an object – this is called making a constructor call, and such functions are generally called constructors: When you call a function with new, four things happen under the hood:
- A new object gets created (let’s call it O);
- O gets linked to another object, called its prototype;
- The function’s this value is set to refer to O;
- The function implicitly returns O.
1 | ; |
Object and Object.prototype
all objects in JavaScript – including Functions – are linked to another object, called its prototype.
If you request a property on an object that the object doesn’t have, JavaScript checks the object’s prototype for that property.
Before the JavaScript engine executes a program, it builds an environment to run it in, in which it creates a function, called Object, and an associated object, called Object.prototype.
Object: The function, Object, is like any other function. In particular, it’s a constructor – calling it returns a new object.
The function, Object, has a property, called .prototype, which points to an object (Object.prototype);
The object, Object.prototype, has a property, called .constructor, which points to a function (Object).
As it turns out, this general scheme is true for all functions in JavaScript. When you create a function – someFunction – it will have a property, .prototype, that points to an object, called someFunction.prototype.
Conversely, that object – someFunction.prototype – will have a property, called .constructor, which points back to the function someFunction.
TBD