Classes in Javascript
Classes are a template for creating objects. They encapsulate data with code to work on that data. Classes in JS are built on prototypes but also have some syntax and semantics that are not shared with ES5 class-like semantics.
Source:
Here are 3 example that display the output of “Son Goku 21”
Example 1.
Using the traditional way of passing values to classes using constructor.
What is a constructor in JavaScript?
A constructor is a function that creates an instance of a class which is typically called an “object”. In JavaScript, a constructor gets called when you declare an object using the
new
keyword.
Source : https://www.educative.io/edpresso/what-is-a-constructor-in-javascript
Example 2.
Passing value using get property method by declaring get property within class Person.
getter ?
The get
syntax binds an object property to a function that will be called when that property is looked up.
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get
Example 3.
Passing value using functions same way as what class method does.
Classes Are Functions
A JavaScript class is a type of function. Classes are declared with the class
keyword. We will use function expression syntax to initialize a function and class expression syntax to initialize a class.
Source: https://www.educative.io/edpresso/what-is-a-constructor-in-javascript
Also another method we can use is using the property of get and set which is most commonly use in every programming.
Output : Son Gohan
There were so many ways on how to write classes on different types of programming languages. Feel free to try. If you want more please leave a comment.
Thank you!