【问题标题】:Determine the type of value of a declared property within a class using RegExp, String or other methods使用 RegExp、String 或其他方法确定类中已声明属性的值的类型
【发布时间】:2018-03-24 14:22:00
【问题描述】:

给定

class MyClass {
    constructor () {
        this.hello = 'greetings';
    }
}

如果不启动class,我们如何确定this.hello 是否应该是JavaScript 类型之一,例如StringArrayBoolean

为了调查的目的,我们不关心程序的实用性,而是关心程序在多大程度上是可能的和可验证的。

例如

let c = MyClass.toString().match(/constructor\s\(?.+\)\s\{?\n.+\n.+\‌​}/); 
c[0].match(/this\.\w+?\s=?\s.*(?:;)/);

我们可以得到this.hello = 'greeting';,接下来的步骤是确定'greeting'应该是或将是一个字符串?

使用RegExpString 方法来实现需求有什么问题?


澄清要求:

给定任意 JavaScript 类,确定其构造函数中使用的参数类型。

【问题讨论】:

  • 使用解析器,解析源代码。不要使用正则表达式来做任何事情。
  • 似乎不是一个可行的方法。例如。 this.hello = 'greetings hi howdy'.split() 意味着helloArray,但要正确处理,您的正则表达式必须能够解释String.prototype.split 返回的内容。 IMO,使用完整的解析器/ AST 比使用正则表达式更幸运。
  • @Tomalak 你能在答案中发表你的观察和建议吗?
  • 这是为了锻炼和好奇,还是无法实例化类的原因是什么?
  • @KevBot 这源于a discussion是否实际上可以通过正则表达式解析Javascript,而后者又源于another question,这并不真正相关。不,没有人知道为什么这个类最初不能被实例化。 ;)

标签: javascript regex string parsing types


【解决方案1】:

不要为此使用正则表达式; 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(`&emsp;Property '${x.expression.left.property.name}' of type '${typeof(x.expression.right.value)}'<br>`));
&lt;script src="//cdnjs.cloudflare.com/ajax/libs/acorn/5.1.2/acorn.js"&gt;&lt;/script&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-17
    • 2020-08-12
    • 1970-01-01
    • 1970-01-01
    • 2016-11-11
    相关资源
    最近更新 更多