define function in a class js code example

Example 1: javascript class

class ClassMates{
	constructor(name,age){
    	this.name=name;
      	this.age=age;
    }
  	displayInfo(){
    	return this.name + "is " + this.age + " years old!";
    }
}

let classmate = new ClassMates("Mike Will",15);
classmate.displayInfo();  // result: Mike Will is 15 years old!

Example 2: 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 3: javascript class

// Improved formatting of Spotted Tailed Quoll's answer
class Person {
	constructor(name, age) {
		this.name = name;
		this.age = age;
	}
	introduction() {
		return `My name is ${name} and I am ${age} years old!`;
	}
}

let john = new Person("John Smith", 18);
console.log(john.introduction());