Left ArrowBack

notes / JavaScript / objects / classes

classes

Profile of a man wearing a top hat & monocle.

JavaScript Classes

Planted

Status: seed

Classes are special functions for creating objects.

/index.js

Console

class MyClass {
  // A field
  a = 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 &
  • 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

Console

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

Console

function MyContructor(a) {
  this.a = a
}

// Creating an instance of MyContructor
const 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

Console

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

Console

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 & 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

Console

class MyClass {
  publicField = 1
  #privateField = 2

  logPrivateField() {
    console.log(this.#privateField)
  }
}

const myClass = new MyClass()

console.log(myClass.publicField)
console.log(myClass.privateField)
myClass.logPrivateField()

The constructor field cannot be private.

Where to Next?

A sci-fi robot taxi driver with no lower body