Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class keyword in Javascript

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?

like image 885
Vladimir Kocjancic Avatar asked Nov 13 '09 12:11

Vladimir Kocjancic


People also ask

What is class keyword JavaScript?

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.

What is class in JavaScript with example?

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.

Why class is used in JavaScript?

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.

Is there class in JavaScript?

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.


1 Answers

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

like image 83
Akhil Arjun Avatar answered Sep 24 '22 08:09

Akhil Arjun