call a function of the class javascript code example

Example 1: javascript new function as class

// Javascript Function that behaves as class, with private variables
function Person(name){
    const birth = new Date();
    this.greet = () => `Hello my name is ${name}. I was born at ${birth.toISOString()}`;
}

const joe = new Person("Joe");
joe.greet(); // Hello my name is Joe. I was born at 2021-04-09T21:12:33.098Z
// The birth variable is "inaccessible" from outside so "private"

Example 2: javascript call class method

'use strict' 
class Polygon { 
   constructor(height, width) { 
      this.h = height; 
      this.w = width;
   } 
   test() { 
      console.log("The height of the polygon: ", this.h) 
      console.log("The width of the polygon: ",this. w) 
   } 
} 

//creating an instance  
var polyObj = new Polygon(10,20); 
polyObj.test();