serialize-javascript
serialize-javascript copied to clipboard
Shorthand method definition fails to serialize and eval property
*properly
When using shorthand to define a function as a method in an object literal, serialization assigns a named function expression, which fails to evaluate.
$ var testSer = { fn1: function(a) { console.log(a); return this; }, fn2: (d) => { console.log(d); return this; }, fn3(r) { console.log(r); return this; } };
Validate the functions first:
test 1
{ fn1: [Function], fn2: [Function], fn3: [Function: fn3] }
$ testSer.fn2('test 2')
test 2
<context>
$ testSer.fn3('test 3')
test 3
{ fn1: [Function], fn2: [Function], fn3: [Function: fn3] }
Do the serialization:
$ ca
'{"fn1":function (a) { console.log(a); return this; },"fn2":(d) => { console.log(d); return this; },"fn3":fn3(r) { console.log(r); return this; }}'
Note how it has created a "fn3"
entry as a named function, but has neglected to add the function
keyword.
Now try to eval
:
$ var c = eval('('+ca+')');
SyntaxError: Unexpected token {
at repl:1:20
at REPLServer.defaultEval (repl.js:262:27)
at bound (domain.js:287:14)
at REPLServer.runBound [as eval] (domain.js:300:12)
at REPLServer.<anonymous> (repl.js:431:12)
at emitOne (events.js:82:20)
at REPLServer.emit (events.js:169:7)
at REPLServer.Interface._onLine (readline.js:211:10)
at REPLServer.Interface._line (readline.js:550:8)
at REPLServer.Interface._ttyWrite (readline.js:827:14)
at ReadStream.onkeypress (readline.js:106:10)
at emitTwo (events.js:87:13)
at ReadStream.emit (events.js:172:7)
at emitKeys (readline.js:1251:14)
at next (native)
at ReadStream.onData (readline.js:919:36)
at emitOne (events.js:77:13)
at ReadStream.emit (events.js:169:7)
at readableAddChunk (_stream_readable.js:153:18)
at ReadStream.Readable.push (_stream_readable.js:111:10)
at TTY.onread (net.js:531:20)
All it needs to do is add the function
keyword:
'{"fn1":function (a) { console.log(a); return this; },"fn2":(d) => { console.log(d); return this; },"fn3": function fn3(r) { console.log(r); return this; }}'
Node version:
$ node -v
v4.4.3
For easier testing, here's a RunKit that reproduces the issue: https://runkit.com/embed/03r03xdac3gn
@wwwslinger is this failing in newer versions of node?
@caridy The RunKit I linked is running Node v6.11.2, and I can also locally repro it on Node 8. I believe the issue is unrelated to the version of Node being used, but am not 100% certain.