2017-10-12 57 views
0

鑑於確定一個類中聲明的屬性的值使用正則表達式,字符串或其他方法

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

類型,我們如何才能確定是否this.hello預計將JavaScript的類型之一,例如,StringArray,Boolean,未啓動class

爲了查詢的目的,我們不關心程序的實用性,而是關心程序在多大程度上是可行和可驗證的。

例如

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

我們可以得到this.hello = 'greeting';,即下一個步驟來確定'greeting'預計或將是一個字符串?

利用RegExpString方法達到要求有什麼問題?


爲明確要求:

鑑於任意JavaScript類,決定在其構造函數中使用的參數的類型。

+1

使用解析器,解析源代碼。不要使用正則表達式來做任何事情。 – Tomalak

+1

似乎不是一種可行的方法。例如。 'this.hello ='問候嗨howdy'.split()'意味着'hello'是一個'Array',但爲了正確使用,你的正則表達式必須能夠解釋什麼'String.prototype.split'回報。國際海事組織,你將有一個完整的解析器/ AST比正則表達式更好。 –

+0

@Tomalak你可以在答覆中發表你的意見和建議嗎? – guest271314

回答

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>`));
<script src="//cdnjs.cloudflare.com/ajax/libs/acorn/5.1.2/acorn.js"></script>

相關問題