[英]Unusual node.js behavior
Today i saw this code, that was running in node.js environment. 今天,我看到了这段代码,该代码在node.js环境中运行。 (>node.exe test.js)
(> node.exe test.js)
var param = (typeof module !== "undefined" && module.exports) || {};
(function(exports){
console.log(exports === module.exports);
})(param);
And this log returned true. 并且此日志返回true。
Can anybody explain me such behavior? 有人可以向我解释这种行为吗?
Thanks in advance. 提前致谢。
If module
is not undefined (which it isn't since it is the default object) and module.exports
is a truthy thing (which it is by default), then exports
is assigned to param
and passed to the function. 如果
module
没有未定义(它不是因为它是默认的对象),并module.exports
是truthy的事情(这是默认设置),然后exports
被分配到param
并传递给函数。
exports
is then compared to module.exports
, and they are the same because module.exports
is where the object came from in the first place. exports
然后比较module.exports
,和他们是一样的,因为module.exports
是对象从在第一时间就来了。
( exports
wouldn't be the same as module.exports
if it was running elsewhere (eg a browser where you get window
, not module
) since {}
would be assigned to param
instead.) (
exports
将与module.exports
如果它在其他地方运行(例如,在浏览器中获取window
而不是module
),因为{}
会被分配给param
。)
Update re comments on the question: 更新关于该问题的评论:
Hmm, maybe it's wrong, but i thought that ((typeof module ..) || {}) will return true, but not "exports" object
嗯,也许是错误的,但是我认为(((typeof module ..)|| {})将返回true,但不会返回“ exports”对象
No. &&
will (working left to right) evaluate as the first falsey thing it tests or (if everything is truthy) the last truthy thing it tests. 否。
&&
将(从左到右工作)评估为它测试的第一个虚假事物,或者(如果一切都是真实的)评估为它测试的最后一个真实事物。
typeof module !== "undefined"
is true so it tests module.exports
, which is also true so it returns module.exports
. typeof module !== "undefined"
为true,因此它测试module.exports
,也为true,因此它返回module.exports
。
(The ||
returns the first truthy or last falsey thing it tests, so it then returns module.exports
) (
||
返回它测试的第一个真实或最后一个虚假的东西,因此它随后返回module.exports
)
var d = (a && b) || c
d
evaluates to b
if a
is true. 如果
a
为真,则d
求值为b
。 If a
is false, d
evaluates to c
. 如果
a
为假,则d
求值为c
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.