Welcome Guest! (App Version 3.1)

websitnero logo name

Classes in ES6

What are Classes?

The concept of classes comes via Object Oriented Programming. Initially there were procedural language like Basic, C, Fortran, etc. Then there were some Procedural languages being developed but a concept of "Object Oriented Programming" arose. Then the concept was merged into developing Procedural langauges and a hybrid was made like in - Java and C++. Later, there were many new langauges which were purely Object-Oriented only like Python, Ruby, Scala, Smalltalk, Eiffel, Emerald, etc.

What Classes do?

Classes are a wrapper or a factory to create Objects with a set of pre-defined properties and methods (to work on those properties). The wrapper consists of a Constructor function which takes a set of parameters as arguments and fixes them as values with the properties that have to be automatically generated.

class Person {
  constructor(someName, someAge, someCountry, sayName){
    this.name = someName;
    this.age = someAge;
    this.country = someCountry;
    this.printName = sayName;
  }
  printAge = function() {
    console.log(this.age);
  }
}

alpha = function(){
  console.log(this.name);
}
James = new Person("James", 23, "USA", alpha);
James.printName();
James.printAge();

Output:

"James"
23

Method in Constructor V Outside

In previous program there were 2 functions associated with an Object created - printName and printAge. You might have noticed they both do the same work conceptually, then what's the difference?

Difference lies in Memory-Management. If you create 10 new Objects (James, Peter, Lily ...) then all those 10 Objects will keep their separate copy for (name, age, country, printName) but will share 1 single memory location holding printAge (this in Vanilla JS will be converted to a Prototype Function). Therefore minimum properties should be added within constructor and wherever you think there can be a common function - like calculating age by DoB or calculating salary of employee by some common formulae - all that should go outside Constructor.

WebsiteNero is highly optimized for learning various website developing technlogies. We try our best to add maximum modules and examples to help learn the concepts clearly and vividly. We try to present all content and examples as simple as we can removing any complexity to hurdle easy understanding. We try best provide you with worthful content, but we cannot guarantee full correctness of all the content on this site. While using this website, you agree to have read and accepted all our terms of use and conditions, cookie, and privacy policy. Copyright, 2013-2018 by websitenero.com. All Rights Reserved.