DEV Community

Cover image for JavaScript: Classes Part-1
Kiran Raj R
Kiran Raj R

Posted on • Edited on

JavaScript: Classes Part-1

Classes are special functions that are used as template for creating objects. Class comprises of variables(data) and function(methods) that use the date to perform some task. If the class contain a constructor method, it is automatically called when we create object using the new operator. Constructor creates properties of the object using variables and methods passed to it (constructor code) in the class declaration and assigns them with the values passed during object creation, there can be only one method with name "constructor". (We use the new operator to create object.) Remember class can be accessed only after class declaration. Like modules class body is executed in strict mode. Basic class syntax is given below.

Classes came into JavaScript in the ES6 specification.

class MyClass {                     //class name

  constructor() {      // class methods
      //constructor code 
  }  

  method1() {
     // code to execute 
  }

  method1() {
     // code to execute 
  }
  ...
}

let obj1 = new Myclass(val1, val2...);  // Object creation
Enter fullscreen mode Exit fullscreen mode

Let's look at an example of a class in JavaScript.

// Class Declaration
class Name {
    constructor(fname, lname) {
        this.fname = fname;
        this.lname = lname;
    }

    printName(){
        console.log(`${this.fname} ${this.lname}`);
    }
}

let myName = new Name("kiran", "raj"); 
myName.printName();                      // kiran raj
let myName1 = new Name("John", "Doe"); 
myName1.printName();                     // John Doe
Enter fullscreen mode Exit fullscreen mode

The above code define a class using class declaration method. We can create class using the class expression method. Class expression methods are of two types named and unnamed. Example of class expression method is provided below.

// Class Expression unnamed
let FriendsName = class {
    constructor(fname, lname) {
        this.fname = fname;
        this.lname = lname;
    }

    printName(){
        console.log(`${this.fname} ${this.lname}`);
    }
}

let Friend1 = new FriendsName("kiran", "raj"); 
Friend1.printName();                      // kiran raj
let Friend2 = new FriendsName("John", "Doe"); 
Friend2.printName();                      // John Doe

// Class expression named
let EnemyName = class FakeFriend{
    constructor(fname, lname) {
        this.fname = fname;
        this.lname = lname;
    }

    printName(){
        console.log(`${this.fname} ${this.lname}`);
    }
}

// let enemy1 = new FakeFriend("kiran", "raj"); 
// Uncaught ReferenceError: FakeFriend is not defined

let enemy2 = new EnemyName("John", "Doe"); 
enemy2.printName();                     // John Doe
Enter fullscreen mode Exit fullscreen mode

Let's look at te code below. THe code contain a class Admin and we created an object kiran using the Admin class. The Admin class contain a constructor which sets the fname, lname with values provided during the object creation and sets isAdmin to true. The Admin class has three methods printName, isAdmin and setUser.

class Admin{
    constructor(fname, lname) {
        this.fname = fname;
        this.lname = lname;
        this.isAdmin = true;
    }

    printName(){
       console.log(`${this.fname} ${this.lname}`);
    }
    isAdmin(){
        if(this.isAdmin){
             console.log("The user is admin");
        } else {
             console.log("The user is admin");
        }
    }
    setUser(){ 
        this.isAdmin = false;
    }
}

let kiran = new Admin("kiran", "raj");
Enter fullscreen mode Exit fullscreen mode

Let's look at typeof Admin and kiran.

console.log(typeof Admin);  //function
console.log(typeof kiran);  //object
Enter fullscreen mode Exit fullscreen mode

Typeof admin is function and typeof kiran is object, we already know that class is a "special function" and it is confirmed by the typeof operator.

When we declare a class the class methods are stored in the className.prototype. In JavaScript objects inherit features from one another using prototypes. When an object is created using new operator the new object get the methods from prototype of the class which used to create the object. Look at the code below, from the code we will understand that Admin stores the class methods in the prototype, which can be accessed by object kiran when it is created using new operator.

console.log(Admin.prototype);
// {constructor: ƒ, printName: ƒ, isAdmin: ƒ, setUser: ƒ}
console.log(Admin === Admin.prototype.constructor); //true
Enter fullscreen mode Exit fullscreen mode

Object.getOwnPropertyNames() returns the array containing all the properties of the given Object.

console.log(Object.getOwnPropertyNames(Admin));
//["length", "prototype", "name"]

console.log(Object.getOwnPropertyNames(kiran)); 
//["fname", "lname", "isAdmin"]

console.log(Object.getOwnPropertyNames(Admin.prototype)); 
//["constructor", "printName", "isAdmin", "setUser"]

Enter fullscreen mode Exit fullscreen mode

JavaScript Classes: Part2- Inheritance
JavaScript Classes: Part3- Getters and Setters

Top comments (4)

Collapse
 
siddharthshyniben profile image
Siddharth

You should learn classes. At first i was like "why would I use classes?". The reason I said this was because I had little practical experience

Collapse
 
kiranrajvjd profile image
Kiran Raj R

I am also learning about classes, it's a big topic. I am still struggling, hope to get more details in the future. I would like to learn from my mistakes, will be happy to get feedbacks.

Collapse
 
siddharthshyniben profile image
Siddharth

In my case, I used classes before i knew what they were, in angular. I guess that made me familiar with it. Anyways, classes are a powerful tool. You should totally spend some time learning about it.

Thread Thread
 
kiranrajvjd profile image
Kiran Raj R

I just started, hope I will some day have better view about classes, thanks bother..