4 ms·
A workaround for this to get the best of the two worlds: let func = () => {};
by gotchange 11y ago
A workaround for this to get the best of the two worlds:
let func = () => {};
- ehynds 11y agoThat seems to do it. let func = () => {}; console.log(func.name); // func and in stack traces: let func = () => foo(); func() results in: Uncaught ReferenceError: foo is not defined func @ test.js:1
- lewisl9029 11y agoWow. I had no idea that would work. All this time I've been using the full named function expressions over arrow functions just for the stack traces.
- ehynds 11y agoStill though, in situations where I care about the stack trace, I don't see myself writing: let doStuffCallback = () => {}; doStuff(doStuffCallback); over: doStuff(function doStuffCallback() { });
- spamizbad 11y agoDoes that only work with something like babel? Because using the node 5.1 repl (and chrome console) you get: > let func = () => {} undefined > func.name '' > function longfunc() {} undefined > longfunc.name 'longfunc'
- Scarbutt 11y agosadly, babel is taken for granted these days.
- lewisl9029 11y agoThe .name property doesn't seem to get set in Firefox either, but error stack traces do show the variable name as the function name. That's the important part IMO.
- gotchange 11y agoHave you tried it with a « var » instead as Chrome imposes certain restrictions on the new ES6 keywords? I also checked the online Babel REPL and verified that it works fine.
- spamizbad 11y agovar results in the same behavior in chrome (empty string for a function name) It looks like babel does this little nicety for stack-trace readability.
- gotchange 11y agoI think Babel converts the code to ES5 and then execute the statements and therefore the function's name is printed to the console just like what you expect from good old ES5 code.
- merpnderp 11y agoWhich is the same as var func = function(){...}.bind(this); no es6 required.
- ehynds 11y agoOP is saying that `let func = () => {};` creates a named function where func.name equals "func" and "func" appears as part of the stack trace. Your example is still an anonymous function just bound to a different context.
- gotchange 11y agoand more verbose as well which was the concern of person to whom I replied.