Babylonian funny import

Since no browser that I know currently implements the ES6 module interface, but transpilers do - I tested babel with this simple example

import { getUsefulContents } from "file.js"; getUsefulContents("http://www.example.com", data => { doSomethingUseful(data); }); 

I just wanted to see how this translates these lines. To my surprise, he produced the following result:

 "use strict"; var _fileJs = require("file.js"); (0, _fileJs.getUsefulContents)("http://www.example.com", function (data) { doSomethingUseful(data); }); 

The last line seems mysterious to me - especially the (0, _fileJs.getUsefulContents) , what happens there? What is the purpose of this (0, ...) on this line?

+6
source share
1 answer

Calling such a function makes it call it in a global context.

 function whoAmI() { document.querySelector('pre').innerText += this.name + '\n'; } window.name = 'window'; var mike = { name: 'mike', whoAmI: whoAmI }; mike.whoAmI(); (0, mike.whoAmI)(); 
 <pre></pre> 

The reason this happens is because when it evaluates (0, filesJs) , it goes through each of the statements in parentheses, much like you can declare multiple variables with ,

 var a = 1, b = 2, ... 

Since the last expression refers to a function, it uses this when evaluating a function call with the following set of parentheses. Since the expression has already been evaluated, the _filesJs context is lost. This is actually the same as it does:

 0; // Legal, just pointless var f = _filesJs.getUsefulContents; f("http://example.com", ...); 
+9
source

Source: https://habr.com/ru/post/989694/


All Articles