javascript - Object.create() 表示参数不是对象

标签 javascript node.js electron

描述

在我的程序中,我正在读取一个 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);

日志

log

问题

当我使用 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/

相关文章:

electron - 从 BrowserWindow 中的预加载脚本访问 webContents

node.js - 构建和打包后,如何在 Electron 应用程序中引用我的 powershell 脚本?

javascript - 递归挑战 - Edabit

Javascript em resize based on window/viewport dimension not affect in-doc style text/css?

javascript - 如何从远程 URL 发送文件作为 Node.js Express 应用程序中的 GET 响应?

Electron 全局快捷方式查找浏览器实例

javascript - 为javascript点击事件传入参数

php - 如何使用 ajax、php 和 html 将一个下拉列表填充到另一个下拉列表中

node.js - 我创建了一个启用了 CORS 的简单 Node 服务器。但是当我执行 node server.js 时,它会抛出错误

javascript - 如何在 node.js 中使用 express 框架提供图像文件?