[英]var exports = module.exports = {} in NodeJS
What I get from previous posts and articles is that the exports object is located on the global
object. 我从以前的文章中可以看到,导出对象位于
global
对象上。 I came across this code which confused me: 我遇到了使我感到困惑的这段代码:
let blue = 'blue'
let red = 'red'
var exports = module.exports = {
red,
blue
};
This code sets module.exports
to a variable called exports
which then gets set to an object which gets exported. 此代码设置
module.exports
一个变量称为exports
然后把它设置为它获取出口的对象。
I am confused however by this syntax: 但是,我对这种语法感到困惑:
Example1: 范例1:
var exports = module.exports = {}
How does this work exactly? 究竟如何运作? Because normally in JS you can't assing a variable two times.
因为通常在JS中,您不能两次修改变量。 For instance this gives an error:
例如,这给出了一个错误:
Example2: 范例2:
let foo = 5 = 4;
How does the code in example 1 give no error while the code in example 2 does? 例2中的代码如何提供示例1中的代码没有错误?
let foo = 5 = 4;
Cause its parsed from right to left: 导致其从右到左解析:
let foo = (5 = 4);
And 5
is not a variable, so you cant assign stuff to it. 而且
5
不是变量,因此您无法为其分配内容。 However it works with an identifier: 但是,它可以与标识符一起使用:
let bar;
let foo = bar = 5;
Your interpretation of what the line is doing is incorrect. 您对生产线正在做什么的解释不正确。
This code sets module.exports to a variable called exports which then gets set to an object which gets exported.
此代码将module.exports设置为一个名为export的变量,然后将其设置为要导出的对象。
What is actually happening is that the value { red, blue }
is being assigned to module.exports
, and then that same value ( { red, blue }
) is being assigned to exports
. 实际情况是,将值
{ red, blue }
分配给module.exports
,然后将相同的值( { red, blue }
)分配给exports
。
In JavaScript and other languages with similar syntax (C, C++, C#, Java) someAssignableThing = someValue
is treated as an expression , and you can use a = b
as a sub-portion of other expressions and chain as many together as you want. 在JavaScript和其他具有类似语法的语言(C,C ++,C#,Java)中,
someAssignableThing = someValue
被视为一个表达式 ,您可以将a = b
用作其他表达式的子部分,并根据需要将a = b
多个链接在一起。
As an expression someAssignableThing = someValue
equates to "assign someValue
to someAssignableThing
and evaluate to the value someValue
". 作为表达式,
someAssignableThing = someValue
等于“将someValue
分配给someAssignableThing
并求值为someValue
”。
So the statement: 所以声明:
a = b = c = d = e = 5;
would assign the value 5
to a
, b
, c
, d
, and e
. 会将值
5
分配给a
, b
, c
, d
和e
。
It is a syntax error to have something on the left side of the =
that cannot be assigned a value and that's why you get an error in the second case (you cannot assign a value to 5
). 在
=
的左边有不能分配值的语法是一种语法错误,这就是为什么在第二种情况下会出错(不能将值分配给5
)的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.