javascript class constructor function code example
Example 1: javascript constructor function
function ClassMates(name,age){
this.name=name;
this.age=age;
this.displayInfo=function(){
return this.name + "is " + this.age + "year's old!";
}
}
let classmate1 = new ClassMates("Mike Will", 15);
classmate.displayInfo();
Example 2: javascript class constructor
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
const person = new Person("John Doe", 23);
console.log(person.name);
Example 3: javascript class
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());
Example 4: javascript class constructor
class Cat {
constructor(name, age) {
this.name = name;
this.age = age;
}
get fullname() {
return this.getFullName()
}
getFullName() {
return this.name + ' ' + this.age
}
}
const run = document.getElementById("run");
run.addEventListener("click", function () {
let Skitty = new Cat('Skitty', 9);
let Pixel = new Cat('Pixel', 6);
console.log(Skitty.getFullName());
console.log(Skitty.fullname);
console.log(Skitty, Pixel);
})
Example 5: javascript classes
class SayHelloTo {
name (to) {
console.log(`Hello ${to}`);
}
constructor (to) {
this.name(to);
}
}
const helloWorld = new SayHelloTo(World);