According to this article it should be a Javascript 2.0 way to define class. However, I never saw that in practice. Thus the question. How to use class keyword and what is the difference between Javascript 1.x way of doing things?
In ES6 the class keyword was introduced. The class keyword is no more than syntactic sugar on top of the already existing prototypal inheritance pattern. Classes in javascript is basically another way of writing constructor functions which can be used in order to create new object using the new keyword.
Note: JavaScript class is a special type of function. And the typeof operator returns function for a class. For example, class Person {} console.log(typeof Person); // function.
Classes serve as templates to create new objects. The most important thing to remember: Classes are just normal JavaScript functions and could be completely replicated without using the class syntax. It is special syntactic sugar added in ES6 to make it easier to declare and inherit complex objects.
JavaScript didn't originally have classes. Classes were added with the introduction of ECMASCRIPT 6 (es6), a new and improved version of JavaScript (ECMASCRIPT 5 being the older version). A typical JavaScript class is an object with a default constructor method.
I know this is a old post, but as of today i.e with the advent of ECMAScript 6 we can declare javascript classes.
The syntax goes as follows :
class Person{ constructor(name){ this.name = name; } printName(){ console.log('Name is '+this.name); } } var john = new Person('John Doe'); john.printName(); // This prints 'Name is John Doe'
A complete guide to this can be found in this post
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With