4 ms·
I wonder what kind of shenanigans you could do with Function.toString(). It'd be even better if they had Function.toAST().
by haecceity 7y ago
I wonder what kind of shenanigans you could do with Function.toString(). It'd be even better if they had Function.toAST().
- tempguy9999 7y agoIn MS's dialect of jscript you could get the function body as a string. That would have been useful in a few cases I'd worked on.
- deleted 7y ago[deleted]
- jefozabuss 7y agoFirst thing I thought about was runtime monkeypatching - while this could be done via simple string replacement during build time (via webpack/rollup etc plugins) now you will be able to do it runtime as well.
- cztomsik 7y agoexactly my thoughts! and if we could construct it too and pass it to the new Function(ast) that would make life easier a lot for tool developers
- k__ 7y agoI saw this used to give JS some new tricks: https://github.com/arrizalamin/js-function-reflector https://github.com/arrizalamin/js-function-reflector
- Nullabillity 7y agoIf I remember correctly, AngularJS 1.x would use it for dependency injection.
- nkozyra 7y agoHow so? Were these eval()ed by Angular? I don't follow what it would use function strings for determining missing - presumably - polyfills that you couldn't do in better ways.
- matsemann 7y agoIn angular 1, if you had a function on the form myApp.controller('MyCtrl', function($myCoolService) { //... }); Angular would see that you are looking for a parameter named myCoolService, see if it already has it, and then inject it when calling your controller. This of course broke in various ways with minification when the parameter names were mangled. So one had the opportunity to use "array syntax", requesting a dependency by a string. Or use a preprocessor in the build script adding the array syntax before minifying.
- wging 7y agoDid it by any chance pull parameter names out by using a magic-number index into the function text? If so, that'd be broken by the 'function /* a comment */ foo () {}' change in the article (and might be what I remember having seen a long time ago). Glad I don't have to deal with that sort of thing. Does Angular 2 do it the same way?
- wging 7y agoLots. I can't remember exactly what I've seen, but believe I have seen it used in interesting ways. Including (drum roll...) .toString().substring(some_magic_number, ...) to do something or other (wish I remembered what). I'll let you think about whether that's wise, but note that indexing into 'function /* a comment */ foo () {}' (the example from the article) will give different results from indexing into 'function foo () {}'.
- haecceity 7y agoIt'd be less magical if you could manipulate the AST instead of the code as a string.