How to import classes in JavaScript

6

When using Node.js to import a serious class:

var Comprobador = require('./comprobador.js');

let comprobador=new Comprobador();

But in pure JavaScript on the client side, how would it be?

    
asked by hubman 24.02.2018 в 06:03
source

2 answers

5

In previous versions of JavaScript there was no way to include JavaScript either by import or require .

The most recent versions added the import and export functionality to meet this point using standards such as ES6 Modules a>, just keep in mind that currently, the browser support for ES6 modules is not very good. To improve this, tools of compilation or transpilation are used. that would be the most recommended.

With these tools it will be easier and the syntax will be similar in some cases equal to the one used in Node

A base example to create a class in one file and import them into another. We create the Person class with a parameter in the constructor and a method

class Persona {
  constructor(nombre) {
    this.nombre = nombre;
  }

  saludar() {
     return "Hola mi nombre es " + this.nombre;
  }
}

export default Persona;

or simply.

export default class  Persona {
  constructor(nombre) {
    this.nombre = nombre;
  }

  saludar() {
     return "Hola mi nombre es " + this.nombre;
  }
}

To call in the other file, just as in your example

import Persona from "./Persona"; // Ruta correcta al archivo Js

let per= new Persona("Stack");
console.log(per.saludar());
    
answered by 24.02.2018 / 06:55
source
4

In ES6 , if you have a class called:

export default class Cliente{
    constructor(nombre, direccion, telefono){
        this.nombre = nombre;
        this.direccion = direccion;
        this.telefono = telefono
    }

    // Getters, setters, etc
}

and this class is in /modulos , you can import it by doing this:

import Cliente from './modulos/Cliente';

You can also import functions, for example, if you have a file called /modulos/Mates.js :

export var suma = function (a, b) {
    return a + b;
}

export var resta = (a, b) => a - b;

export var multiplicar = (a, b) => a * b;

//etc

you can import functions like this:

import {suma, resta, multiplicar} from './modulos/Mates';
    
answered by 24.02.2018 в 06:38