简体   繁体   中英

Pure Functions In JavaScript ES6

For some unknown reason, I can't get object spread to work in my code. I'm having to fall back on 'Object.assign()', but would rather use '...'

The following works:

const frederick = {
  name: 'Frederick Douglass',
  canRead: false,
  canWrite: false
};

// create new object and mutate that one
const selfEducate = person =>
  Object.assign({}, person,
    {canRead:true},
    {canWrite:true}
  );

console.log(selfEducate(frederick));  // { name: 'Frederick Douglass', canRead: true, canWrite: true }
console.log(frederick);  // { name: 'Frederick Douglass', canRead: false, canWrite: false }

However, the following does not:

const frederick = {
  name: 'Frederick Douglass',
  canRead: false,
  canWrite: false
};

const selfEducate = person =>
  ({
    ...person,
    canRead: true,
    canWrite: true
  });

console.log(selfEducate(frederick));
console.log(frederick);

That one errors out with:

SyntaxError: Unexpected token ...

The spread operator does work in other code of mine that involves copying arrays, but not in this example. Any feedback would be appreciated.

If your other parts of code are working with the spread operator against arrays, that's not the same as trying to spread an object literal.

There's proposals for the spec to have it, such as here .

Please try the following steps.

Installation

npm install --save-dev babel-plugin-transform-object-rest-spread

Usage in existing presets

"plugins": ["transform-object-rest-spread"]

Reference link: Click here

NB: The object spread operator is not a default feature. It requires transpiler as above.

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