简体   繁体   中英

Why arrow functions don't work when using import/export

This code shows "show not defined."

import {a} from './dis.js';
show = () =>{
  console.log(a);
}
show();

But this works

import {a} from './dis.js';
const show = () =>{
    console.log(a);
}
show();

why is that ?

This is not related to the arrow functions. It's the nature of strict code. You can see an example when I work in the strict mode. What about ES6 modules, they are automatically in strict mode.

 'use strict'; show = 4; 

You are trying to assign a reference of an arrow function to a variable show which is not defined. Defined means that you have defined it with keyword var , let or const for variables.

In the first code part you haven't declare it with these keywords, it tries to find the variable and doesn't find anything defined with that name. So it throws error.

In the second code part you have defined a variable with name show and then assign to it a reference to an arrow function. So everything is OK.

This is not due to arrow function. You are trying to assign a value to show , but have not defined that variable anywhere. Define it using var , let or const

While assigning without defining works in JS, it is not recommended, and not allowed in strict mode.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM