Understanding JavaScript classes is not limited to just TypeScript; it delves into the core workings of JavaScript itself. Essentially, classes in JavaScript are nothing more than functions.
Introduced as part of the ECMAScript 6 standard in 2015, classes are primarily a syntactic sugar that simplifies an established JavaScript practice of mimicking classes. For instance, the following code snippet:
class MyClass {
constructor(myProp) {
this.myProp = myProp;
}
print() {
console.log(this.myProp);
}
}
achieves similar functionality as this:
function MyClass(myProp) {
this.myProp = myProp;
}
MyClass.prototype.print = function () {
console.log(this.myProp);
};
JavaScript classes essentially boil down to being functions. But how exactly does it all work?
The fundamental idea is this: every time a JavaScript function is called, a hidden this
parameter is passed to the function:
- Calling a function by itself (
myFunction()
) sets this
to the global object (typically window
on browsers).
- Using the dot notation while calling a function (
myObject.myFunction()
) assigns this
to the respective object (myObject
).
- Invoking a function with the
new
keyword (new myFunction()
) entails creating a new object and setting this
to point to the newly created object.
Additionally, there's the concept of prototypes in JavaScript. Objects in JS have a property known as the prototype. When utilizing the dot notation, if the requested property isn't found in the object, it's then sought after in the prototype. If still not found, the search continues up the prototype chain. The new func()
syntax aligns the prototype of the freshly created object with func.prototype
. Therefore, when you write:
var myObject = new MyClass("propValue");
myObject.print();
the print
method is first searched for within myObject
and then in MyClass.prototype
.
This prototype-based approach to OOP offers great flexibility but has often been perplexing for programmers accustomed to class-based languages. To mitigate confusion, numerous libraries were developed to mimic classes, eventually paving the way for their official integration into JavaScript in 2015.
Hence, the essence of why a class is essentially just a function in the realm of JavaScript.