How to make a simple class...

 

function Foo() { 
  this.name = "foo"; 
} 

Foo.prototype.sayHello = function() { 
    alert("hello from " + this.name); 
}; 
 
var myFoo = new Foo(); myFoo.sayHello();
 

 

 


class Person {
  constructor(name, age) {
    this.name = name
    this.age = age
  }


  sayHello() {
    console.log( `Helllo ${this.name} - ${this.age}` )
  }
}


var person1 = new Person("Ivan", 21)
var person2 = new Person("Fred", 23)

person.sayHello()
// Hello Ivan

 

Advantages of classes:

  • Object Creation
  • Encapsulation
  • Inheritance
  • Code Reusability
  • Polymorphism
  • Abstraction