In ECMAScript 2015 or later versions, we can create a class in JavaScript using the class
keyword. A class is essentially a syntax for creating objects with predefined properties and methods.
To define a class, we first need to use the class
keyword followed by the name of the class. Here's an example:
index.tsx163 chars11 lines
In the above code, we have defined a Person
class with a constructor that takes in two parameters name
and age
. We have also defined a method sayHello
which logs a greeting to the console.
To create an instance of a class, we simply use the new
keyword followed by the name of the class and any arguments required by the constructor. Here's an example:
index.tsx101 chars3 lines
In the above code, we have created a new instance of the Person
class and passed in the arguments 'John Doe'
and 30
.
We can also add methods to a class using the prototype
property. Here's an example:
index.tsx133 chars6 lines
In the above code, we have added a sayAge
method to the Person
class using the prototype
property. We can then call this method on any instance of the Person
class, such as johnDoe
.
gistlibby LogSnag