简体   繁体   English

Javascript 在 if

[英]Javascript assining a function to other function on if

I'm reading a Nodejs book and I came accross to this syntax below我正在阅读一本 Nodejs 书,我遇到了下面的这种语法

function createClient (ns, opts) {
  return createClient[ns] || (createClient[ns] = nos(net.connect(opts)))
}

Didn't quite understand the createClient[ns] = nos(net.connect(opts)) part, What it means?不太明白createClient[ns] = nos(net.connect(opts))部分,是什么意思? Why should I use it?我为什么要使用它?

Is this syntax documented anywhere?这种语法是否记录在任何地方?

This is taking advantage of the ability to chain the assignment operator to assign values to multiple variables at once.这利用了链接赋值运算符的能力,可以一次将值分配给多个变量。 Stated another way, the return value of an assignment expression is the value that was assigned.换句话说,赋值表达式的返回值就是被赋值的值。

The simplest demonstration is to the log the output of an assignment operation:最简单的演示是记录 output 的赋值操作:

 console.log(test = 'foo');

This behavior is mentioned in the MDN docs for the assignment operator : 赋值运算符的 MDN 文档中提到了此行为:

Chaining the assignment operator is possible in order to assign a single value to multiple variables为了将单个值分配给多个变量,可以链接赋值运算符

In your code snippet, the intention seems to be "return the value of createClient[ns] unless it's false (eg unassigned), otherwise assign the value of nos(net.connect(opts)) to createClient[ns] and return that value."在您的代码片段中,意图似乎是“返回createClient[ns]的值,除非它为假(例如未分配),否则将nos(net.connect(opts))的值分配给createClient[ns]并返回该值。”

This is a simple form of caching and implies that nos() is an expensive operation that shouldn't be repeated unless necessary.这是一种简单的缓存形式,意味着nos()是一项昂贵的操作,除非必要,否则不应重复。

Here's a simplified example:这是一个简化的示例:

 let values = {}; function assignIfNotSet(arg) { return values['example'] || (values['example'] = arg); } console.log('before:'); console.log(values); let result = assignIfNotSet('foo'); console.log('after:'); console.log(values); console.log('result: ' + result);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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