js can we use functions in a class 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: Using functions in Class
class Student{
int scores[5];
public:
void input(){
for(int i=0; i<5; i++){
cin >> scores[i];
}
}
int calculateTotalScore(){
int total = 0;
for(int i=0; i<5; i++){
total += scores[i];
}
return total;
}
};