contructor javascript 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: 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 3: why do we use Object Constructors
function Tree(name) {
this.name = name
}
let theTree = new Tree('Redwood')
console.log('theTree.constructor is ' + theTree.constructor)