[英]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. 当我在
strict
模式下工作时,您可以看到一个示例。 What about ES6
modules, they are automatically in strict
mode. ES6
模块呢,它们会自动进入strict
模式。
'use strict'; show = 4;
You are trying to assign a reference of an arrow function to a variable show
which is not defined. 您试图将箭头功能的引用分配给未定义的变量
show
。 Defined means that you have defined it with keyword var
, let
or const
for variables. Defined表示您已使用关键字
var
, let
或const
了变量。
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. 在第二个代码部分中,您定义了一个名为show的变量,然后为其分配了对箭头函数的引用。 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. 您正在尝试为
show
分配一个值,但尚未在任何地方定义该变量。 Define it using var
, let
or const
使用
var
, let
或const
定义它
While assigning without defining works in JS, it is not recommended, and not allowed in strict
mode. 当在JS中分配但未定义作品时,不建议这样做,并且在
strict
模式下也不允许这样做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.