javascript constructor 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: metodo constructor javascript
class miClase {
constructor(primero, segundo) {
this.uno = primero;
this.dos = segundo;
this.tres = "Hola a todos";
};
miMetodoUno() {
return this.dos;
}
miMetodoDos(parametroUno, parametroDos) {
console.log(
"El parametro UNO es: " + parametroUno +
"<br>El parametro DOS es: " + parametroDos
)
}
}
var objetoUno = new miClase("Antonio", 56);
objetoUno.miMetodoDos("Manuel", 44);
Example 3: es6 class example
<script>
class Student {
constructor(rno,fname,lname){
this.rno = rno
this.fname = fname
this.lname = lname
console.log('inside constructor')
}
set rollno(newRollno){
console.log("inside setter")
this.rno = newRollno
}
}
let s1 = new Student(101,'Sachin','Tendulkar')
console.log(s1)
s1.rollno = 201
console.log(s1)
</script>
Example 4: 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 5: 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 6: javascript classes
class MyClass {
constructor(FirstProperty, SecondProperty, etcetera) {
this.firstProperty = FirstProperty;
this.secondProperty = SecondProperty;
}
method(Parameters) {
}
get getBothValues()
{
return [firstProperty, secondProperty];
}
}