how to get a variable from another js file

0

I have the following problem: I am working with several javaScript files and I want to recover the contents of the variable that is generated in another js file .. example in the file1.js is executed and in a function that is found there is generated the value for a variable that is declared at the beginning of the js but in the file2.js after the file1 is executed. in the file2.js I need to get the value q generated in the file1.js, it should be mentioned that the scripts are linked to the main page but I could not recover that value marks me empty or undefined or null I hope you can help me :)

thanks in advance

    
asked by Oliver Peres 13.12.2017 в 00:46
source

1 answer

1

You can use ECMAscript6 and the import statement is used to import functions that have been exported from an external module. (It means variables too).

Syntax

 import defaultExport from "module-name";
 import * as name from "module-name";
 import { export } from "module-name";
 import { export as alias } from "module-name";
 import { export1 , export2 } from "module-name";
 import { export1 , export2 as alias2 , [...] } from "module-name";
 import defaultExport, { export [ , [...] ] } from "module-name"; 
 import defaultExport, * as name from "module-name";
 import "module-name";

Imports a single member of a module.

Given an object or value named myExport that has been exported from the module my-module either implicitly (because the entire module has been exported) or explicitly (using the export statement), this inserts myExport in the current scope.

 import {myExport} from '/modules/my-module.js';

I hope you help greetings.

  

Note: to use import and to work in all browsers you can use Webpack and Babel since it does not yet have support in all the Browsers

Examples

Import a secondary file to assist in processing an AJAX JSON request.

The module: file.js

function getJSON(url, callback) {
 let xhr = new XMLHttpRequest();
 xhr.onload = function () { 
callback(this.responseText) 
 };
 xhr.open('GET', url, true);
 xhr.send();
 }

 export function getUsefulContents(url, callback) {
  getJSON(url, data => callback(JSON.parse(data)));
}

The main program: main.js

 import { getUsefulContents } from '/modules/file.js';

  getUsefulContents('http://www.example.com',
    data => { doSomethingUseful(data); });

Source: MDN

    
answered by 13.12.2017 в 00:53