class with constructor javascript 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 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: constructor in js
A constructor is a function that creates an instance of a class
which is typically called an “object”. In JavaScript, a constructor gets
called when you declare an object using the new keyword.
The purpose of a constructor is to create an object and set values if
there are any object properties present.
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 MyClass {
constructor(FirstProperty, SecondProperty, etcetera) {
this.firstProperty = FirstProperty;
this.secondProperty = SecondProperty;
}
method(Parameters) {
}
get getBothValues()
{
return [firstProperty, secondProperty];
}
}
Example 6: javascript class
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
get area() {
return this.calcArea();
}
calcArea() {
return this.height * this.width;
}
}
const square = new Rectangle(10, 10);
console.log(square.area);