描述
在我的程序中,我正在读取一个 JSON 文件,将其解析为一个对象,然后尝试使用 Object.create()
将其“转换”为 ProjectFile
类的对象。
代码
let tmpFileContent = fs.readFileSync(tmpPath, {encoding: 'utf-8'});
let tmpObject = JSON.parse(tmpFileContent);
console.log(tmpObject);
fileList[fileList.length] = Object.create(ProjectFile, tmpObject);
日志
问题
当我使用 console.log(tmpObject);
输出 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
}
});
最佳答案
Object.create 函数获取原型(prototype)作为第一个参数,属性描述符作为第二个参数。
您的第二个参数类型错误。您需要传递一个对象,该对象包含具有以下属性的对象:可配置
、可写
、可枚举
及其值
。
参见示例。在第二种情况下,当我传递一个不适用于所需形状的参数时,它会给我同样的错误。
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'
});
关于javascript - Object.create() 表示参数不是对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46173919/