Class methods
Closed this issue · 7 comments
Parsing class methods seems to yield empty bodies, anonymous names and empty arg lists.
Example:
'use strict';
var parseFunction = require('parse-function');
class EqualityChecker {
isEqual(a, b) {
return a === b;
}
}
var checker = new EqualityChecker();
console.log('Prototype:', parseFunction(EqualityChecker.prototype.isEqual));
console.log('Instance:', parseFunction(checker.isEqual));Both console.logs will print { name: 'anonymous', args: [], params: '', body: '' }.
I suspect it is because .toString() on methods returns the exact representation from the code, from the first to the last token, so in our case (tabs originally in the string):
isEqual(a, b) {
return a === b;
}The same problem occurs with this compacted ES6 "function-less" notation:
parseFunction({
isEqual(a, b) {
return a === b;
}
}.isEqual)Hey, very thanks! I'll look into it, I think we just should look more on acorn ast.
I'm starting to think it may be acorn issue.
acorn.parse(EqualityChecker.prototype.isEqual.toString(), {ecmaVersion: 7})throws a syntax error. Or maybe this is the reason why acorn.parse_dammit exists. And that's why I using it, because such cases. I'm looking on ast that parse_dammit returns for that, may need more ifs in the walk :)
There are few ways:
- detect if result of
toString()begins withfunctionor at least the letterfand if not prepend it - add
ifin the walk to listen toCallExpression
Second feels kinda wrong to me and I'm thinking it would mess the things more than it solve them.
What you think about the fix?
edit: Ooops, labels should stay.
As much as I am bewildered by the choice of substring check mechanism ([0] and [1] - I assume it's for performance reasons), this is exactly the workaround that I did in my code:
let functionString = methodFunction.toString();
if (functionString.slice(0, 8) !== 'function') {
functionString = 'function ' + functionString;
}I agree that it is the sane thing to do. Checking for function calls is probably best left alone - there is another npm module for that (extracts call parameters), and it may be wise not to expand into that field.
Yea.
extracts call parameters
You can try http://npm.im/function-arguments, it works for regular, generator and arrow functions. If you need support only for regular functions can use Sindre's fn-args, it's lighter and probably faster.
It would be better choice to use one of them if you only need getting arguments.
Oh sorry, i forget to publish. I doing it now :) v2.3.2