ES6 class in javaScript

Object-Oriented Programming was created with the class idea, and a class is a blueprint that defines the variables and the methods common to all objects of a certain kind.

With ECMAScript 6, JavaScript has the class keyword. What is ECMAScript? It is a JavaScript standard meant to ensure the interoperability of Web pages across different Web browsers.

class People {
    constructor(name, country, language) {
        this.name = name;
        this.country = country;
        this.language = language;
    }
    speak() {
        return this.name + " can speak " + this.language;
    }
}

const tim = new People("Tim", "USA", "english");
console.log(tim);
console.log(tim.speak());
console.log(tim.__proto__);
console.log(tim.__proto__.__proto__);
People { name: 'Tim', country: 'USA', language: 'english' }
Tim can speak english
People {}
{}

The beauty with classes is that as Object-Oriented programming suggests we want to keep all our functionalities and all the state inside of the box. Class is a nice contained environment.

In JavaScript, the language is still using prototypal inheritance. JavaScript is not using classes like classes work in other languages. JavaScript was competing with Java for marketing purposes they could not make it the exact same. So, Brendan Eich had to be creative. So, he used prototypal Inheritance which is quite different from how classes work in Languages like Java and c++. In other languages classes are an actual thing, but JavaScript classes are still just object.

You can say JavaScript has classes, but class keyword is still just prototypal inheritance.

Also, const tim = new People("Tim", "USA", "english"); if you use new keyword, it instantiate a class.

Methods in Class

speak() {
    return this.name + " can speak " + this.language;
}

that is going to take up memory space. Instead of creating an speak function from each object. you can have on function in one location that all the instances of class can access.

Object.create() vs Class

There is a big debate in the JavaScript Community. People that love classes and people that never want to use new and this keyword. This is just a personal preference. With Object.create(), we are able to create prototypal inheritance without pretending like we have classes. However, most of the JavaScript community does not use Object.create() as much as class.

Leave a Reply

Your email address will not be published.

ANOTE.DEV