描述
在我的程序中,我正在读取一个JSON文件,将其解析为一个对象然后我尝试"施放"使用ProjectFile
将其转换为班级Object.create()
的对象。
代码
let tmpFileContent = fs.readFileSync(tmpPath, {encoding: 'utf-8'});
let tmpObject = JSON.parse(tmpFileContent);
console.log(tmpObject);
fileList[fileList.length] = Object.create(ProjectFile, tmpObject);
日志
问题
当我使用tmpObject
输出console.log(tmpObject);
时,它表示它是日志中的对象。在之后的行中,我尝试将其用作对象,该对象应该被转换为类ProjectFile的对象,但它显示错误消息,它不是对象。我做错了什么?
编辑:ProjectFile类
class ProjectFile {
constructor(p_name, p_path, p_type, p_thumnailPath) {
this.name = p_name;
this.path = p_path;
this.thumnailPath = p_thumnailPath;
}
}
编辑2:工作代码
let tmpFileContent = fs.readFileSync(tmpPath, {encoding: 'utf-8'});
let tmpObject = JSON.parse(tmpFileContent);
console.log(tmpObject);
fileList[fileList.length] = Object.create(ProjectFile, {
name: {
value: tmpObject.name,
writable: true,
enumerable: true,
configurable: true
},
path: {
value: tmpObject.path,
writable: true,
enumerable: true,
configurable: true
},
thumnailPath: {
value: tmpObject.thumnailPath,
writable: true,
enumerable: true,
configurable: true
}
});
答案 0 :(得分:3)
Object.create函数将原型作为第一个参数和属性描述符作为第二个参数。
您的第二个参数类型错误。您需要传递一个对象,该对象包含具有configurable
,writable
,enumerable
和value
属性属性的对象。
参见示例。在第二种情况下,当我传递一个不适用于所需形状的参数时,它会给我同样的错误。
const pr = { name: 'Name' };
const successChild = Object.create( pr, {
surname: {
value: 'Surname',
writable: true,
enumerable: true,
configurable: true
}
});
console.log(successChild);
const errorChild = Object.create( pr, {
name: 'Error Name',
surname: 'Error Surname'
});