
JavaScript Classes
Planted:
Status: decay
Hits: 198
Classes are special functions for creating objects.
index.js
class MyClass {// A fielda = 1}const myObj = new MyClass(1)console.log(myObj)console.log(typeof myObj)
new
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:
- ▪ create a new object,
- ▪ the object is
[[Prototype]]
-linked to the function, - ▪ the returned object is set as the
this
binding for that function call and - ▪ unless the function returns its own alternate object, the new-invoked function call will automatically return the newly constructed object.
Constructor
The constructor
method is a special field for initializing an object created with a class.
index.js
class MyClass {constructor(a) {this.a = a}}const myObj = new MyClass(1)console.log(myObj)
function
The behaviour of a class can be replicated using a plain function.
index.js
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)
Extending
Using the extend
keyword, a class can extend another class.
This removes the need to rewrite functionality you want to use across multiple classes.
index.js
class Parent {constructor(a) {this.a = a}}class Child extends Parent {}const child = new Child(1)console.log(child.a)
super
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.
index.js
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)console.log(child.b)
Public and Private
Fields are public by default.
Prefixing a field with a #
will make them private.
Private fields can only be accessed within the class.
index.js
class MyClass {publicField = 1#privateField = 2logPrivateField() {console.log(this.#privateField)}}const myClass = new MyClass()console.log(myClass.publicField)console.log(myClass.privateField)myClass.logPrivateField()
The constructor
field cannot be private.
Feedback
Have any feedback about this note or just want to comment on the state of the economy?