javascript constructor code example

Example 1: metodo constructor javascript

//CREAR UNA CLASE
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
        )
    }
}
//CREAR UN OBJETO - instanciar
var objetoUno = new miClase("Antonio", 56);
//RECUPERAR DATOS
objetoUno.miMetodoDos("Manuel", 44);

Example 2: 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(); // "Mike Will is 15 year's old!"

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()); // Skitty 9
      	console.log(Skitty.fullname); // Skitty 9 => shorter syntax
        console.log(Skitty, Pixel); 
      // Object { name: "Skitty", age: 9} Object {name: "Pixel", age:6}
    })

Example 5: js constructor object

function Car(make, model, year) {
  this.make = make;
  this.model = model;
  this.year = year;
}

var car1 = new Car('Eagle', 'Talon TSi', 1993);

console.log(car1.make);
// expected output: "Eagle"

Example 6: javascript constructor object

function Person(first, last, age, eye) {
  this.firstName = first;
  this.lastName = last;
  this.age = age;
  this.eyeColor = eye;
}

Tags:

Java Example