Javascript tips — Class vs Instance properties
Sep 5, 2018 · 1 min read

This post is just a small tip about ES6+ properties. We can find in many languages instance and class (static) fields. Let’s see an example:
1 — Instance property
class Employee {
constructor() {
this.Name = "Leonardo Lima";
}
}const emp = new Employee();console.log(emp.Name); //output Leonardo Lima
console.log(Employee.Name); //output undefined
This code above we just create a class and defined a instance field called Name and this field is accessible only via instance, emp variable. We can rewrite this code removing the constructor:
class Employee {
Name = "Leonardo Lima";
}const emp = new Employee();console.log(emp.Name); //output Leonardo Lima
console.log(Employee.Name); //output undefined
2 — Class property
In order to create a class property, we need to create the field using static keyword:
class Employee {
static Name = "Leonardo Lima";
}const emp = new Employee();console.log(emp.Name); //output undefined
console.log(Employee.Name); //output Leonardo Lima
As you can see in the code above, now the Name field is accessible directly via class and you cannot access it using the instance emp.
Thanks for reading!
