Javascript tips — Class vs Instance properties

Leonardo Bruno Lima
Sep 5, 2018 · 1 min read
Photo by Pankaj Patel on Unsplash

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!

Leonardo Bruno Lima

Written by

Full stack developer | NodeJs, .Net, ReactJs, Angular and Javascript addicted. https://www.linkedin.com/in/lblima | https://github.com/lblima

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade