简体   繁体   中英

es6 syntax for factory

Could someone please explain how the following es6 code is a factory.

const createChat = ({
  id = 0,
  msg = '',
  user = 'Anonymous',
  timeStamp = 1472322852680
} = {}) => ({
  id, msg, user, timeStamp
});

All the values you see ( 0 , '' , Anonymous , 1472322852680 ) are the default values. They would normally be extracted from the passed in object but if they don't exist these are what will be used in their place. This is default parameters .

The => ({...}) is shorthand to return the value (notice there is no return statement). So here it is returning an object with the passed in id , msg , user , and timeStamp unless those values aren't passed in. It is accomplishing this by using destructing .

https://jsfiddle.net/y7mb6jsp/

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