确定一个类中声明的属性的值使用正则表达式,字符串或其他方法
问题描述:
鉴于确定一个类中声明的属性的值使用正则表达式,字符串或其他方法
class MyClass {
constructor() {
this.hello = 'greetings';
}
}
类型,我们如何才能确定是否this.hello
预计将JavaScript的类型之一,例如,String
,Array
,Boolean
,未启动class
?
为了查询的目的,我们不关心程序的实用性,而是关心程序在多大程度上是可行和可验证的。
例如
let c = MyClass.toString().match(/constructor\s\(?.+\)\s\{?\n.+\n.+\}/);
c[0].match(/this\.\w+?\s=?\s.*(?:;)/);
我们可以得到this.hello = 'greeting';
,即下一个步骤来确定'greeting'
预计或将是一个字符串?
利用RegExp
或String
方法达到要求有什么问题?
为明确要求:
鉴于任意JavaScript类,决定在其构造函数中使用的参数的类型。
答
不要使用正则表达式;对于简单的正则表达式来说,JavaScript语法的复杂性太多了。相反,使用解析器并行走AST。
下面是使用acorn的一个非常粗略的刺戳。这将只捕获以下形式声明的属性:
this.<propName> = <literal>;
但它表明了基本概念。
class MyClass {
constructor() {
this.hello = 'greetings';
}
}
var ast = acorn.parse(MyClass.toString());
document.write(`Class: '${ast.body[0].id.name}'<br>`);
var ctor = ast.body[0].body.body.find(fn => fn.kind == "constructor");
ctor.value.body.body.forEach(x =>
x.type == "ExpressionStatement" &&
x.expression.type == "AssignmentExpression" &&
x.expression.left.type == "MemberExpression" &&
x.expression.left.object.type == "ThisExpression" &&
x.expression.left.property.type == "Identifier" &&
x.expression.right.type == "Literal" &&
document.write(` Property '${x.expression.left.property.name}' of type '${typeof(x.expression.right.value)}'<br>`));
<script src="//cdnjs.cloudflare.com/ajax/libs/acorn/5.1.2/acorn.js"></script>
使用解析器,解析源代码。不要使用正则表达式来做任何事情。 – Tomalak
似乎不是一种可行的方法。例如。 'this.hello ='问候嗨howdy'.split()'意味着'hello'是一个'Array',但为了正确使用,你的正则表达式必须能够解释什么'String.prototype.split'回报。国际海事组织,你将有一个完整的解析器/ AST比正则表达式更好。 –
@Tomalak你可以在答复中发表你的意见和建议吗? – guest271314