



Planted:
Status: decay
Classes are special functions for creating objects.
class MyClass {// A fielda = 1}const myObj = new MyClass(1)console.log(myObj) // MyClass { a: 1 }console.log(typeof myObj) // object
The new operator creates an instance of a user-defined object type or of one of the built-in object types that has a constructor function.
When a function is invoked with new in front of it, we call it a constructor call.
It will:
[[Prototype]]-linked to the function,this binding for that function call andThe constructor method is a special field for initializing an object created with a class.
class MyClass {constructor(a) {this.a = a}}const myObj = new MyClass(1)console.log(myObj) // MyClass { a: 1 }
The behaviour of a class can be replicated using a plain function.
function MyContructor(a) {this.a = a}// Creating an instance of MyContructorconst myObj = new MyContructor(1)// The prototype of "myObj" will be "MyContructor"console.log(myObj) // MyContructor { a: 1 }
Using the extend keyword, a class can extend another class.
This removes the need to rewrite functionality you want to use across multiple classes.
class Parent {constructor(a) {this.a = a}}class Child extends Parent {}const child = new Child(1)console.log(child.a) // 1
If the child uses a contructor method, the super keyword needs to be called before this can be used.
It will invoke the parent's contructor method.
class Parent {constructor(a) {this.a = a}}class Child extends Parent {constructor(a, b) {super(a)this.b = b}}const child = new Child(1, 2)console.log(child.a) // 1console.log(child.b) // 2
Fields are public by default.
Prefixing a field with a # will make them private.
Private fields can only be accessed within the class.
class MyClass {publicField = 1#privateField = 2logPrivateField() {console.log(this.#privateField) // 2}}const myClass = new MyClass()console.log(myClass.publicField) // 1console.log(myClass.privateField) // undefinedmyClass.logPrivateField()
The constructor field cannot be private.
Have any feedback about this note or just want to comment on the state of the economy?

