我正在使用一个js工具,该工具将从一个对象生成Js类文件(myclass.js),例如:
myObj = { width: 0,
height: 0,
getWidth: [Function],
getHeight: [Function] }
我想生成一个包含类的js文件myClass.js:
class MyClass {
constructor (width, height) {
this.width = width;
this.height = height;
}
getWidth () { return this.width ; }
getHeight () { return this.height; }
}
我认为myObj.construct.toString()返回类的所有代码,但是仅当“ myObj”是该类的实例时才起作用,在我的情况下,“ MyObj”将动态生成。
答案 0 :(得分:1)
您必须遍历myObj
的所有键,然后根据那里的每个值自己生成+连接代码。用意大利面条写的粗略实现看起来像:
function objectToClassString(obj = {}, className = 'MyClass') {
const opener = `class ${className} {`
const closer = '}'
const indent = (str: string) => str.replace(/^(.*)/gm, ' $1')
const ctorArgs = [] // array of `{ argName }` objects
const getterMethods = [] // array of `{ methodName, property }` objects
for (const key in obj) {
const value = obj[key]
if (Array.isArray(value) && value[0] === Function) {
getterMethods.push({ methodName: key, property: key.replace(/^get(.)/, (_, letter) => letter.toLowerCase()) })
} else {
ctorArgs.push({ argName: key })
}
}
const ctorOpener = `constructor(${ctorArgs.map(data => data.argName).join(', ')}) {`
const ctorContent = ctorArgs.map(data => `this.${data.argName} = ${data.argName};`).join('\n')
const ctorCloser = '}'
const ctor = [ctorOpener, indent(ctorContent), ctorCloser].join('\n')
const methods = getterMethods
.map(data => `${data.methodName}() { return this.${data.property}; }`)
.join('\n')
const classContent = [
opener,
indent(ctor),
indent(methods),
closer
].join('\n')
return classContent
}
用法:
const code = objectToClassString({
width: 0,
height: 0,
getWidth: [Function],
getHeight: [Function]
})
console.log(code)
输出:
class MyClass {
constructor(width, height) {
this.width = width;
this.height = height;
}
getWidth() { return this.width; }
getHeight() { return this.height; }
}