js function in class 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();
Example 2: javascript new function as class
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();
Example 3: es6 class example
'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)
}
}
var polyObj = new Polygon(10,20);
polyObj.test();
Example 4: javascript create class
class Car {
constructor(brand) {
this.carname = brand;
}
}
Example 5: 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;
}
};