JavaScript Fundamentals: Advanced Classes

What are class methods? how do you use class methods? what are some common default class methods you should know about.

JavaScript Fundamentals: Advanced Classes
JavaScript Fundamentals: Advanced Classes

A class is a type of object in JavaScript. A class is a template for creating objects. Objects are created from classes. Classes are defined by the keyword class, and a class can be created by using the keyword new.

In JavaScript, methods are associated with objects. Objects can have any number of methods associated with them. Here are some object methods you should know to help leverage your classes.

Class methods are called on the class itself, and not on an instance of the class. To call a class method, you would use the name of the class, followed by the method name, like this:

ClassName.methodName();

Class methods are functions that are associated with a class. In JavaScript, there are several ways to create a class, but the most common method is to use the keyword "class."

Class methods are declared inside the class body. They can be used to perform various tasks, such as initializing the class, validating data, or performing calculations.

JavaScript constructors and destructors

Constructors and destructors are often glossed over when it comes to classes in JavaScript. Here are the reasons why they are important:

  • Constructors are important in JavaScript classes because they define the properties and methods that will be available to each instance of the class.
  • Destructors are important because they allow the programmer to clean up any resources that were allocated during the lifetime of the object.

Writing a constructor in JavaScript

The constructor method is used to initialize the class. It is called when an instance of the class is created.

For example, the following class has a constructor that takes two parameters:

class Car {
  constructor(make, model, year) {
    this.make = make;
    this.model = model;
   this.year = year;
  }
}

The Car class constructor takes in three arguments - make, model, and year. These arguments are used to initialize the instance variables of the same name. In this way, the constructor allows us to create new Car objects with specific make, model, and year values.

Writing a destructor in JavaScript

The destructor method is used to release resources when an instance of the class is destroyed.
class ClassName {

   constructor(name) {
    this.name = name;
   }

   destructor() {
      // This function is called when the object is destroyed
     console.log(`${this.name} is destroyed`);
   }
}

A destructor is important to run in JavaScript because it helps to ensure that all memory associated with an object is freed when the object is no longer needed. This can help to prevent memory leaks, which can lead to performance issues.

Class object methods

A class object method is a function associated with a class. Class object methods are important because they allow us to create objects that have their own methods. This means that we can create objects that can perform actions on their own, without having to rely on global functions.

Here is a list of JavaScript class object methods and what they do.

hasOwnProperty()

The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it).

For example:

class MyClass {
  constructor() {
    this.prop1 = 'Hello';
  }
}

const obj = new MyClass();

console.log(obj.hasOwnProperty('prop1')); // true
console.log(obj.hasOwnProperty('toString')); // false

isPrototypeOf()

The method isPrototypeOf() checks whether the prototype of a constructor is in the prototype chain of an object.

This method returns true if the constructor's prototype is in the prototype chain of the object, otherwise it returns false.

For example:

class A {}
class B {}

A.prototype = B.prototype;

var a = new A();

console.log(B.prototype.isPrototypeOf(a)); // true

propertyIsEnumerable()

The class object method propertyIsEnumerable() is used to check if a specified property is enumerable.

class MyClass {
 
  constructor(prop1, prop2) {
    this.prop1 = prop1;
    this.prop2 = prop2;
  }
 
  myMethod() {
    // do something
  }
 
}
 
let myObj = new MyClass('val1', 'val2');
 
console.log(myObj.propertyIsEnumerable('prop1')); // true
console.log(myObj.propertyIsEnumerable('prop2')); // true
console.log(myObj.propertyIsEnumerable('myMethod')); // false

toLocaleString()

The toLocaleString() method returns a string representation of the object. This method is usually invoked by calling toString() on an object.

The toLocaleString() method is different from the toString() method in that it tries to return a string that is suitable for the locale of the environment in which the method is being called.

For example, if you have a Date object in the US English locale, calling toLocaleString() on that object will return a string in the US English format, whereas calling toString() on the same object will return a string in the ISO 8601 format.

Here is a basic example of the toLocaleString() method:

class MyClass {
   toLocaleString() {
      return "MyClass";
   }
}

let myObj = new MyClass();

console.log(myObj.toLocaleString()); // MyClass

toString()

The toString() method returns a string representation of the object.

For example:

class Car {
  toString() {
    return 'Car';
  }
}

let car = new Car();
console.log(car.toString()); // 'Car'

valueOf()

The valueOf() method returns the primitive value of a given object.

For example,

class Test {
  constructor(value) {
    this.value = value;
  }
  valueOf() {
    return this.value;
  }
}

const test1 = new Test(10);
console.log(test1.valueOf()); // 10

toFixed()

The toFixed() method returns a string representation of a number, with the specified number of decimal places.

class MyClass {
  toFixed(x) {
    return x.toFixed(2);
  }
}

let myObj = new MyClass();
console.log(myObj.toFixed(2.55)); // 2.55

toExponential()

The toExponential() method returns a string representing the Number object in exponential notation.

var x = 9.656;

console.log(x.toExponential()); // Returns 9.656e+0

console.log(x.toExponential(2)); // Returns 9.66e+0

console.log(x.toExponential(4)); // Returns 9.6560e+0

console.log(x.toExponential(6)); // Returns 9.656000e+0

toPrecision()

The toPrecision() method returns a string representing the number object it was called on, using exponential notation if necessary.

If the number is less than 1, the number will be multiplied by 10 until it is greater than or equal to 1, and the exponent will be negative.

If the number is greater than or equal to 1, the number will be divided by 10 until it is less than 1, and the exponent will be positive.

The toPrecision() method will always return a string with at least one digit before the decimal point.

Here is an example of the toPrecision() method being used:

class MyClass {
  toPrecision(x) {
    return x.toPrecision();
  }
}

let myObj = new MyClass();
console.log(myObj.toPrecision(2)); // 2.0
console.log(myObj.toPrecision(4)); // 2.000
console.log(myObj.toPrecision(6)); // 2.000000

toJSON()

The toJSON() method is used to convert a JavaScript object into a JSON string. The following code shows how to use the toJSON() method:

class MyClass {
  toJSON() {
    return { foo: 'bar' };
  }
}

const myObj = new MyClass();

console.log(JSON.stringify(myObj)); // {"foo":"bar"}

toSource()

The toSource() method returns a string representing the source code of the object.

class Rectangle {
  constructor(width, height) {
    this.width = width;
    this.height = height;
  }
}

console.log(Rectangle.toSource());
// logs "[class Rectangle]"

watch()

The watch() method watches for a property to be assigned a value and runs a function when that occurs.

class MyClass {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  watch() {
    console.log(`${this.name} is ${this.age} years old.`);
  }
}

const myObj = new MyClass("John", 30);
myObj.watch(); // John is 30 years old.

unwatch()

The unwatch() method removes a watchpoint from a property of the object.

💡
Want to check out my other stuff? See my link wall at Zipply.io.