Episode 6: Work with Classes in Modern JavaScript Development | Salesforce ☁️⚡️


 Prior to ES6, if you wanted to create a class in JavaScript, you used prototypes to do something similar to this:

1
2
3
4
5
6
7
function Animal(name) {
  this.name = name;
}
      
Animal.prototype.printName = function() {
  console.log(this.name);
}

And you can call this function or class using this standard way

1
2
let duck = new Animal('duck');
duck.printName();  // Displays "duck"  

ES6 added class keyword and unlike other traditional object-oriented supporting languages like java or c++ ,class keyword in Javascript. Still under the hood it’s just a special function. Let’s try it out with the same example.

1
2
3
4
5
6
7
8
9
class Animal {
  constructor(name) {
    this.name = name;
  }
    
  printName() {
    console.log(this.name);
  }
}  

This is the new syntax if you want to use class in the JavaScript but what more surprisingly is that it also supports inheritance 


Classes come in two flavors: base classes and derived classes. The difference is the extends keyword. Derived classes (also known as subclasses) have them, and base classes don't. Take, for example, the following base class named Parent.


1
2
3
4
5
6
7
8
9
class Parent {
  constructor(name) {
    this.name = name;
  }
      
  getName() {
    return this.name;
  }
}

Assume you needed to create a subclass named Child that extends the functionality available in the Parent class. It might look something like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Child extends Parent {
  constructor(name) {
    super(name);
  }
        
  getMessage() {
    return 'Hello ' + super.getName();
  }
}
      
let someone = new Child('person');
console.log(someone.getMessage());     // Displays "Hello person"


Resource : https://trailhead.salesforce.com/content/learn/modules/modern-javascript-development/work-with-classes?trail_id=learn-to-work-with-javascript


Checkout complete video tutorial below

 If you have any question please leave a comment below.

If you would like to add something to this post please leave a comment below.
Share this blog with your friends if you find it helpful somehow !

Thanks
Happy Coding :)

Post a Comment

0 Comments