We will learn about ES6 class syntax. and we will use in our react component.
Goal: To reuse the code.
What is Class?
It is a blueprint or template for Javascript objects. We will be able to make multiple instances of the class for the individual items.
It always add a method named constructor()
class ClassName{
constructor(){
}
}
The constructor function will be invoked automatically when an new object created.
Rules for constructor:
- The constructor is a special function
- It should have exact name "constructor"
- Its executed when we create object
- They are named with capital letter first.
- It is used to initialize object props
- If we dont add constructor function javascript will add an empty constructor
- They should be executed only with
"new"
operator.
When a function is executed with new
, it does the following steps:
- A new empty object is created and assigned to
this
. - The function body executes. Usually it modifies
this
, adds new properties to it. - The value of
this
is returned.
class Person{
constructor(name){
this.name = name;
}
}
const me = new Person('Praba');
console.log(me);
Individual instance of the Person we will use this keyword to access the property.
We can create multiple instances.
const me = new Person('Praba');
const others = new Person('karan');
const him = new Person();
If we dont pass any argument this will throw undefined.
We can also add some conditions in constructor.
class Person{
constructor(name){
this.name = name || 'Karan';
}
}
const me = new Person('Praba');
console.log(me);
We can also set argument with default value in the constructor.
class Person {
constructor(name = 'Anonymous') {
this.name = name;
}
getMyName(){
return $this.name;
}
}
const me = new Person('Prabakaran');
console.log(me.getMyName());
Class Methods:
class methods are created same syntax as object methods.
class Person {
constructor() {
}
methodName(){
}
}
How to access method?
class Person {
constructor(name = 'Anonymous') {
this.name = name;
}
getMyName(){
return this.name;
}
}
const me = new Person('Prabakaran');
console.log(me.getMyName());
Another feature ES6 Strings .
- It will allow us to create better strings ``.
- we can inject anything inside `` backticks
class Person {
constructor(name = 'Anonymous') {
this.name = name;
}
getMyName(){
return `{$this.name}`;
}
}
const me = new Person('Prabakaran');
console.log(me.getMyName());
We will see how to create ES6 subclass in the next tutorial.
Comments
Post a Comment