我需要创建一个方法GetCode
,返回一个字符串,其中包含任何类的构造函数的源代码。例如,
let code = GetCode (class CX {
constructor () {
this.x = 1
this.y = 1
this.fx ()
this.fy ()
}
fx () {}
fy () {}
})
应该在code
变量中返回与此类似的内容:
`
this.x = 1
this.y = 1
this.fx ()
this.fy ()
`
对于像fx
或fy
这样的常规方法,一个简单的.toString
调用就足够了。但是,当对构造函数函数执行此操作时,返回的字符串是类的整个文本,而不是函数的内部源代码。我曾尝试使用JSCodeShift
等工具解析CX.toString ()
返回的字符串,以获取我需要的文本片段,但指纹太重(5Mb(。
我想知道是否有可能设计一个破解来获得我需要的源代码的字符串。
其他示例:
let code = GetCode (class CX {
constructor ({ min, max }) {
if (min < max) {
for (let x = min; x < max; x++) {
console.log (x)
}
}
this.min = min
this.max = max
}
fmin () { return this.min }
fmax () { return this.min }
})
所以,我得到了解决方案。遵循以下步骤-
- 获取Class并使用
toString()
将其转换为字符串 - 使用regexp获取结果字符串的
constructor
部分 - 将子字符串分解为数组。执行
pop()
和shift()
以移除阵列中不必要的部分 - 最后,将数组连接为字符串
下面的片段解释了这一切-
console.log(getCode(class CX {
constructor () {
this.x = 1;
this.y = 1;
this.fx ();
this.fy ();
}
fx () {}
fy () {}
}));
console.log(getCode(class CX {
constructor ({ min, max }) {
if (min < max) {
for (let x = min; x < max; x++) {
console.log (x)
}
}
this.min = min
this.max = max
}
fmin () { return this.min }
fmax () { return this.min }
}));
function getCode(inputClass){
let regx = /constructor[sS]+?(?=}n[A-Za-zs*]*()[s]*{)/g;
let code = inputClass.toString();
let arr = code.match(regx)[0].split("n");
arr.pop();
arr.shift();
return arr.join("n");
}